Vue.js父与子组件之间传参示例
例子:App.vue为父,引入componetA组件之后,则可以在template中使用标签(注意驼峰写法要改成componet-a写法,因为html对大小写不敏感,componenta与componentA对于它来说是一样的,不好区分,所以使用小写-小写这种写法)。而子组件componetA中,声明props参数'msgfromfa'之后,就可以收到父向子组件传的参数了。例子中将msgfromfa显示在<p>标签中。
App.vue中
<component-amsgfromfa="(JustSayULoveMe)"></component-a>
importcomponentAfrom'./components/componentA' exportdefault{ newVue({ components:{ componentA } }) }
componentA.vue中
<p>{{msgfromfa}}</p>
exportdefault{ props:['msgfromfa'] }
父向子组件传参(.$broadcast)
用法:vm.$broadcast(event,[…args])广播事件,通知给当前实例的全部后代。因为后代有多个枝杈,事件将沿着各“路径”通知。
例子:父组件App.vue中<input>绑定了键盘事件,回车触发addNew方法,广播事件”onAddnew”,并传参this.items。子组件componentA中,注册”onAddnew”事件,打印收到的参数items。
App.vue中
<divid="app"> <inputv-model="newItem"@keyup.enter="addNew"/> </div>
importcomponentAfrom'./components/componentA' exportdefault{ newVue({ methods:{ addNew:function(){ this.$broadcast('onAddnew',this.items) } } }) }
componentA.vue中
importcomponentAfrom'./components/componentA' exportdefault{ 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>Doyoulikeme?{{childWords}}</p> <component-amsgfromfa="(JustSayULoveMe)"v-on:child-say="listenToMyBoy"></component-a>
importcomponentAfrom'./components/componentA' exportdefault{ newVue({ data:function(){ return{ childWords:"" } }, components:{ componentA }, methods:{ listenToMyBoy:function(msg){ this.childWords=msg } } }) }
componentA.vue中
<buttonv-on:click="onClickMe">like!</button>
importcomponentAfrom'./components/componentA' exportdefault{ data:function(){ return{ msg:'Ilikeyou!' } }, 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>Doyoulikeme?{{childWords}}</p> <component-amsgfromfa="(JustSayULoveMe)"></component-a>
importcomponentAfrom'./components/componentA' exportdefault{ newVue({ events:{ 'child-say':function(msg){ this.childWords=msg } } }) }
componentA.vue中
<buttonv-on:click="onClickMe">like!</button>
importcomponentAfrom'./components/componentA' exportdefault{ data:function(){ return{ msg:'Ilikeyou!' } }, methods:{ onClickMe:function(){ this.$dispatch('child-say',this.msg); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。