例子:App.vue為父,引入componetA組件之后,則可以在template中使用標簽(注意駝峰寫法要改成componet-a寫法,因為html對大小寫不敏感,componenta與componentA對于它來說是一樣的,不好區分,所以使用小寫-小寫這種寫法)。而子組件componetA中,聲明props參數'msgfromfa'之后,就可以收到父向子組件傳的參數了。例子中將msgfromfa顯示在<p>標簽中。
App.vue中
<component-a msgfromfa="(Just Say U Love Me)"></component-a>
import componentA from './components/componentA'export default {new Vue({components: {componentA}})} componentA.vue中
<p>{{ msgfromfa }}</p> export default {props: ['msgfromfa']} 父向子組件傳參(.$broadcast)
用法:vm.$broadcast( event, […args] )廣播事件,通知給當前實例的全部后代。因為后代有多個枝杈,事件將沿著各“路徑”通知。
例子:父組件App.vue中<input>綁定了鍵盤事件,回車觸發addNew方法,廣播事件”onAddnew”,并傳參this.items。子組件componentA中,注冊”onAddnew”事件,打印收到的參數items。
App.vue中
<div id="app"><input v-model="newItem" @keyup.enter="addNew"/></div>
import componentA from './components/componentA'export default {new Vue({methods: {addNew: function() {this.$broadcast('onAddnew', this.items)}}})}componentA.vue中
import componentA from './components/componentA'export default {events: {'onAddnew': function(items){console.log(items)}}} 子組件向父傳參(.$emit)
用法:vm.$emit( event, […args] ),觸發當前實例上的事件。附加參數都會傳給監聽器回調。
例子:App.vue中component-a綁定了自定義事件”child-say”。子組件componentA中,單擊按鈕后觸發”child-say”事件,并傳參msg給父組件。父組件中listenToMyBoy方法把msg賦值給childWords,顯示在<p>標簽中。
App.vue中
<p>Do you like me? {{childWords}}</p><component-a msgfromfa="(Just Say U Love Me)" v-on:child-say="listenToMyBoy"></component-a>import componentA from './components/componentA'export default {new Vue({data: function () {return {childWords: ""}},components: {componentA},methods: {listenToMyBoy: function (msg){this.childWords = msg}}})}componentA.vue中
<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'export default {data: function () {return {msg: 'I like you!'}},methods: {onClickMe: function(){this.$emit('child-say',this.msg);}}}子組件向父傳參(.$dispatch)
用法:vm.$dispatch( event, […args] ),派發事件,首先在實例上觸發它,然后沿著父鏈向上冒泡在觸發一個監聽器后停止。
例子:App.vue中events中注冊”child-say”事件。子組件componentA中,單擊按鈕后觸發”child-say”事件,并傳參msg給父組件。父組件中”child-say”方法把msg賦值給childWords,顯示在<p>標簽中。
App.vue中
<p>Do you like me? {{childWords}}</p><component-a msgfromfa="(Just Say U Love Me)"></component-a>import componentA from './components/componentA'export default {new Vue({events: {'child-say' : function(msg){this.childWords = msg}}})}componentA.vue中
<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'export default {data: function () {return {msg: 'I like you!'}},methods: {onClickMe: function(){this.$dispatch('child-say',this.msg);}}}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答