鍍金池/ 問答/HTML/ vue.compile字符串模板如何解析@click方法

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不執(zhí)行。。。

如果修改為${fun()}有報錯

Invalid handler for event "click": got undefined

有沒一種方法可以是的能夠編譯處理,并且點擊能正確執(zhí)行fun? 我現(xiàn)在用的是把fun方法data里面

回答
編輯回答
單眼皮
`<el-button type="primary" @click="console.log('afe')">查詢</el-button>`

最簡單的辦法, 直接把 fun 的函數(shù)體寫進@click 里面.

@click="content" 會被編譯成這樣子:

{
  onclick: function () {
    content
  }
}

所以你的寫法會變成

{
  onclick: function () {
    function fun() {
      console.log('afe')
    }
  }
}

借助IIFE, 這樣寫

`<el-button type="primary" @click="(${fun})()">查詢</el-button>`

// 結果
{
  onclick: function () {
    (function fun() {
      console.log('afe')
    })()
  }
}
2017年2月16日 01:08