Vue的自定義組件不能使用click方法的解決
先貼代碼
var myButton = Vue.extend({//設(shè)置標簽 props: [’names’, ’item2’],//names為按鈕名,item2為數(shù)據(jù) template: ’<span><span v-for='obj in item2' v-if='obj.name==names' v-html='obj.code'></span></span>’ }) Vue.component(’my-button’, myButton);//注冊組件
這是上篇博客的自定義按鈕權(quán)限的代碼,然后調(diào)用代碼:
<my-button names='修改' v-bind:item2='btdata'></my-button>
當你在這個標簽上加@click事件的時候報錯,原因是因為沒有加上native,官網(wǎng)對于native的解釋為:
.native - 監(jiān)聽組件根元素的原生事件。
正確的代碼為:
<my-button @click.native='alert1()' names='刪除' v-bind:item2='btdata'></my-button>
這樣就能成功在自定義標簽上綁定事件了
補充知識:Vue中利用component切換組件
我就廢話不多說了,大家還是直接看代碼吧~
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>Document</title> <script src='http://www.lshqa.cn/bcjs/vue.js'></script></head><body> <div id='app'> <a href='http://www.lshqa.cn/bcjs/11206.html#' rel='external nofollow' rel='external nofollow' @click='componentName=’mycom1’'>組件1</a> <a href='http://www.lshqa.cn/bcjs/11206.html#' rel='external nofollow' rel='external nofollow' @click='componentName=’mycom2’'>組件2</a> <component :is='componentName'></component> </div></body><script> Vue.component(’mycom1’,{ //注意無論是哪種方式創(chuàng)建組件,template都只能有一個唯一的根元素 template: ’<h3>組件1</h3>’,//指定組件要展示的html結(jié)構(gòu) }) Vue.component(’mycom2’,{ //注意無論是哪種方式創(chuàng)建組件,template都只能有一個唯一的根元素 template: ’<h3>組件2</h3>’,//指定組件要展示的html結(jié)構(gòu) }) //創(chuàng)建一個vue實例 //當我們導入包之后,在瀏覽器的內(nèi)存中就多了一個vue構(gòu)造函數(shù) var vm = new Vue({ el: ’#app’,//表示當前我們new的這個vue實例要控制頁面上的哪個區(qū)域 data: { //data屬性中存放的是el中要用到的數(shù)據(jù) componentName: ’mycom1’ } }); </script></html>
以上這篇Vue的自定義組件不能使用click方法的解決就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
