vue.compile字符串模板如何解析@click方法

let compileStr = Vue.compile(this.templateString)this.template = compileStr.render
templateString: function (scope) {
      let fun = function () {
        console.log('afe')
      }      return `        <div>
          <el-button type="primary" @click="${fun}">查询</el-button>
          <el-button type="primary">详情</el-button>
        </div>
      `
    }

点击后fun不执行。。。

如果修改为${fun()}有报错

Invalid handler for event "click": got undefined

有没一种方法可以是的能够编译处理,并且点击能正确执行fun? 我现在用的是把fun方法data里面


MYYA
浏览 2549回答 1
1回答

慕森王

`<el-button&nbsp;type="primary"&nbsp;@click="console.log('afe')">查询</el-button>`最简单的办法, 直接把 fun 的函数体写进@click 里面.@click="content" 会被编译成这样子:{&nbsp;&nbsp;onclick:&nbsp;function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;content &nbsp;&nbsp;} }所以你的写法会变成{&nbsp;&nbsp;onclick:&nbsp;function&nbsp;()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;function&nbsp;fun()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log('afe') &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} }借助IIFE, 这样写`<el-button&nbsp;type="primary"&nbsp;@click="(${fun})()">查询</el-button>`//&nbsp;结果{ &nbsp;&nbsp;onclick:&nbsp;function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;(function&nbsp;fun()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log('afe') &nbsp;&nbsp;&nbsp;&nbsp;})() &nbsp;&nbsp;} }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Vue.js