Vue的自定義組件不能使用click方法的解決
先貼代碼
var myButton = Vue.extend({//設置標簽 props: [’names’, ’item2’],//names為按鈕名,item2為數據 template: ’<span><span v-for='obj in item2' v-if='obj.name==names' v-html='obj.code'></span></span>’ }) Vue.component(’my-button’, myButton);//注冊組件
這是上篇博客的自定義按鈕權限的代碼,然后調用代碼:
<my-button names='修改' v-bind:item2='btdata'></my-button>
當你在這個標簽上加@click事件的時候報錯,原因是因為沒有加上native,官網對于native的解釋為:
.native - 監聽組件根元素的原生事件。
正確的代碼為:
<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.cgvv.com.cn/bcjs/vue.js'></script></head><body> <div id='app'> <a href='http://www.cgvv.com.cn/bcjs/11206.html#' rel='external nofollow' rel='external nofollow' @click='componentName=’mycom1’'>組件1</a> <a href='http://www.cgvv.com.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’,{ //注意無論是哪種方式創建組件,template都只能有一個唯一的根元素 template: ’<h3>組件1</h3>’,//指定組件要展示的html結構 }) Vue.component(’mycom2’,{ //注意無論是哪種方式創建組件,template都只能有一個唯一的根元素 template: ’<h3>組件2</h3>’,//指定組件要展示的html結構 }) //創建一個vue實例 //當我們導入包之后,在瀏覽器的內存中就多了一個vue構造函數 var vm = new Vue({ el: ’#app’,//表示當前我們new的這個vue實例要控制頁面上的哪個區域 data: { //data屬性中存放的是el中要用到的數據 componentName: ’mycom1’ } }); </script></html>
以上這篇Vue的自定義組件不能使用click方法的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. springcloud alibaba nacos linux配置的詳細教程2. Vue為什么要謹慎使用$attrs與$listeners3. SpringBoot 使用 @Value 注解讀取配置文件給靜態變量賦值4. Java 生成帶Logo和文字的二維碼5. SpringBoot整合MybatisPlus的教程詳解6. 解決在Vue中使用axios POST請求變成OPTIONS的問題7. Spring Boot2發布調用REST服務實現方法8. python 實現圖片修復(可用于去水印)9. Android自定義控件實現方向盤效果10. python中的socket實現ftp客戶端和服務器收發文件及md5加密文件
