之前關于vue.js2.0父組件的一點學習,最近需要回顧,就順便發到隨筆上了
<body> <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:ee="incrementTotal"></button-counter> <button-counter v-on:ee="incrementTotal"></button-counter> </div> <script> Vue.component('button-counter', { template: '<button v-on:click="increment">{{ counter }}</button>', data: function () { return { counter: 0 } }, methods: { increment: function () { this.counter += 1 this.$emit('ee', 'cc' ) } }, }) new Vue({ el: '#counter-event-example', data: { total: 'arg' }, methods: { incrementTotal: function (b) { this.total = b + '1'; } } }) </script> </body> 子組件通過$emit觸發父組件的事件,$emit后面的參數是向父組件傳參,注意,父組件的事件處理函數直接寫函數名即可,不要加(),參數直接傳遞到了父組件的methods的事件處理函數了。
另外,寫一個小拾遺。vue子組件用了定義模板組件功能,然后在父組件里定義一個HTML元素綁定這個子組件后才能在父組件通過這個HTML元素使用。
再說一個非常方便的v-ref
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="vue.js"></script> </head> <body> <div id="parent"> <input type="text" name="" id="" v-model="msg" /> <input type="button" id="" value="dianji" @click="clickDt" /> <user-profile ref="profile"></user-profile> </div> <script> Vue.component('user-profile', { template: '<span>{{ msg }}</span>', data: function () { return { msg: 123 }; }, methods: { greet: function (msg) { console.log(msg); } } }) // var parent = new Vue({el: '#parent'}); // var child = parent.$refs.profile; // child.greet(); new Vue({ el:"#parent", data:{ msg:"" }, methods: { clickDt(){ this.$refs.profile.greet(this.msg); } } }) </script> </body> </html> Vue2.0組件間數據傳遞
Vue1.0組件間傳遞
Vue2.0后$dispatch(),$broadcast()被棄用,見https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替換
1,父組件向子組件傳遞場景:Father上一個輸入框,根據輸入傳遞到Child組件上。
新聞熱點
疑難解答
圖片精選