組件間通信(父子,兄弟)
相關鏈接/組件通信:點擊查看
學習鏈接:Vue.js——60分鐘快速入門點擊查看
分分鐘玩轉Vue.js組件點擊查看
父組件傳子組件
父傳子方法(一) 屬性傳遞 props
//子組件<template> <ul> <li v-for="item in dataList">{{item}}</li> </ul> </template><script> export default { props : { dataList : [] } }</script>//父組件<template> <component-child v-bind:data-list="dataList"> </component-child> <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script>import ComponentChild from './child.vue'export default { data () { return { dataInput: "", dataList : [ 'hello world!','welcome to use vue.js' ] } }, components : { ComponentChild }, methods : { addDataItem () { let self = this if( !(self.dataInput && self.dataInput.length > 0) ) { return } self.dataList.push( self.dataInput ) self.dataInput = "" } }}</script>父傳子方法(二) 廣播事件傳遞 vm.$broadcast
//子組件<template> <ul> <li v-for="item in dataList">{{item}}</li> </ul> </template><script>export default { data () { return { dataList : [ 'hello world!', 'welcome to use vue.js' ] } }, events : { addChildDataEvent : function ( dataInput ) { this.dataList.push( dataInput ) } }}</script>//父組件<template> <component-child></component-child> <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script> import ComponentChild from './child.vue' export default { data () { return { dataInput: "" } }, components : { ComponentChild }, methods : { addDataItem () { let self = this if( !(self.dataInput && self.dataInput.length > 0) ) { return } //廣播到子組件 self.$broadcast( 'addChildDataEvent', self.dataInput ) self.dataInput = "" } } }</script>子組件傳父組件
子傳父方法 派遣事件傳遞 vm.$dispatch
//子組件<template> <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script> export default { data () { return { dataInput: "" } }, methods : { addDataItem () { let self = this if( !(self.dataInput && self.dataInput.length > 0) ) { return } //派遣事件到父組件 self.$dispatch( 'addFatherDataEvent', self.dataInput ) self.dataInput = "" } } }</script>//父組件<template> <ul> <li v-for="item in dataList">{{item}}</li> </ul> <component-child></component-child></template><script>import ComponentChild from './child.vue'export default { data () { return { dataList : [ 'hello world!', 'welcome to use vue.js' ] } }, components : { ComponentChild }, events : { addFatherDataEvent : function ( dataInput ) { this.dataList.push( dataInput ) } }}</script>
新聞熱點
疑難解答
圖片精選