vue
1、父传子
通过props静态或动态传递值
<blog-post title="My journey with Vue"></blog-post>
<blog-post v-bind:title="post.title"></blog-post>//注意post.title此时为变量,不是字符串
复制代码
"Fu":{
props:["title"],//子组件把该变量存入props数组
data:function(props){//在data里使用props时,需要传入参数props
return{
fu:props.la,
can:"",
hua:""
}
},
methods:{
haha(a){
this.can = a;
console.log(this.can);
},
asd(a){
this.hua=a
}
},
created(){
console.log("aaaa");
},
template:
`<div>
<h1 >hello world----{{this.can}}</h1>
<p>我是父组件----{{fu}} </p>
<p>平行组件-------{{this.hua}}</p>
<Zi :data="fu" @lala="haha" @aq="asd"></Zi>
</div>`,
复制代码
2、子传父
在父组件的根元素上直接监听一个原生事件
<my-component v-on:my-event="doSomething"></my-component>复制代码
然后在子组件的点击事件里触发事件
this.$emit('myEvent')复制代码
3、平行组件之间通信
var vm = new Vue({});//新建一个空的vue实例,通过在这个实例上绑定和触发事件,在平行组件之间通信
var app = new Vue({
el:"#box",
data:{
str3:"",
str4:""
},
methods:{
},
components:{
"x-one":{
template:"#one",
data:function(){
return {
str:"我是one",
stt:"hello"
}
},
methods:{
onec:function(){
vm.$emit("one",this.stt)//在onec方法中触发one事件
}
}
},
"x-two":{
template:"#two",
data:function(){
return {
str1:"我是two",
srr:"world"
}
},
methods:{
twoc:function(){
vm.$emit("two",this.srr)//在onec方法中触发tewc事件
}
}
},
"x-three":{
template:"#three",
data:function(){
return {
str2:"我是three",
str3:"",
str4:""
}
},
mounted:function(){
var that = this;
vm.$on("one",function(data){
that.str3=data;
})
vm.$on("two",function(data){//在该组件的挂载钩子函数里绑定two事件
that.str4=data;
})
}
}
}
})
复制代码