父子 props和$emit
父组件向子组件传值,在子组件的标签上绑定要传的值,子组件使用props来接收
子组件想父组件传值,在子组件的标签上绑定事件在实例中定义方法来接受
Vue.component('child',{
data(){
return {
mymessage:this.message
}
},
template:`
<div>
<input type="text" v-model="mymessage" @input="passData(mymessage)"> </div>
`,
props:['message'],//设置props属性值,得到父组件传递过来的数据
methods:{
passData(val){
//触发父组件中的事件,向父组件传值
this.$emit('getChildData',val)
}
}
})
//父组件
Vue.component('parent',{
template:`
<div>
<p>this is parent compoent!</p>
//向子组件传递message 接受子组件的值并使用getChildData来接受
<child :message="message" v-on:getChildData="getChildData"></child>
</div>
`,
data(){
return {
message:'hello'
}
},
methods:{
//执行子组件触发的事件
getChildData(val){
console.log(val)
}
}
})
bus
定义一个vue实力
在其他组件中使用bus.emit来触发事件传值
Vue.component('brother1',{
data(){
return {
mymessage:'hello brother1'
}
},
template:`
<div>
<p>this is brother1 compoent!</p>
<input type="text" v-model="mymessage" @input="passData(mymessage)">
</div>
`,
methods:{
passData(val){
//触发全局事件globalEvent
bus.$emit('globalEvent',val)
}
}
})
Vue.component('brother2',{
template:`
<div>
<p>this is brother2 compoent!</p>
<p>brother1传递过来的数据:{{brothermessage}}</p>
</div>
`,
data(){
return {
mymessage:'hello brother2',
brothermessage:''
}
},
mounted(){
//绑定全局事件globalEvent
bus.$on('globalEvent',(val)=>{
this.brothermessage=val;
})
}
})
//中央事件总线
var bus=new Vue();
var app=new Vue({
el:'#app',
template:`
<div>
<brother1></brother1>
<brother2></brother2>
</div>
`
})
provide和inject
在嵌套多层的组件中除了使用vuex还可以使用provide和inject
父组件使用provide传入数据给子组件
子组件使用inject导入数据
Vue.component('child',{
inject:['for'],//得到父组件传递过来的数据
data(){
return {
mymessage:this.for
}
},
template:`
<div>
<input type="tet" v-model="mymessage">
</div>
`
})
Vue.component('parent',{
template:`
<div>
<p>this is parent compoent!</p>
<child></child>
</div>
`,
provide:{
for:'test' //向子组件注入数据
},
data(){
return {
message:'hello'
}
}
})