vue组件传值在日常开发中比较常见,在官方文档里面也有介绍,但是对于新手理解起来会有一点生涩。所以今天就把这个拉出来写一次。
一般有三种传值方式:1.父传子、2.子传父、3.兄弟组件之间通信
1.父组件向子组件传值
一般会在子组件里面定义props来做接收,这是比较常见的情况
这是父组件
我是父组件 我发送给第一个组件的信息是:{{msg}}import ChildOne from "../components/children1";
import ChildTwo from "../components/children2";
export default {
components: {
ChildOne,
ChildTwo
},
data() {
return {
msg: "我是父组件,我给你发消息",
};
}
};
可以看到我在第一个子组件上面传入了一个msg,那么在子组件上就需要定义一个msg用来接收传进来的参数
这是第一个子组件
我是第一个子组件 我接受到的父组件的消息是:{{msg}}export default {
props: {
msg: {
type: String
}
}
};
效果
父传子.png
2.子组件向父组件传值
这时候就需要利用vue中的$emit将想要传递的值通过函数的形式传出,在父组件接收
this.$emit(arg1,arg2) arg1:方法名字,arg2:要传出的值
这是第二个子组件
我是第二个子组件 我要发送给父组件的值:{{msg}}向父组件发送信息
export default {
data() {
return {
msg: "我是第二组件,我要给父组件传值",
};
},
methods: {
toParent() {
this.$emit("toParent", this.msg);
}
}
};
我在button上绑定了一个点击事件,函数里面传出了一个方法名为toParent的方法,这时候我们就要去父组件接收这个函数,它会带一个返回值,这个返回值就是我们需要从子组件传的值。
这是父组件
我是父组件 我即将接收第二组件传值是:{{child2Msg}}import ChildOne from "../components/children1";
import ChildTwo from "../components/children2";
export default {
components: {
ChildOne,
ChildTwo
},
data() {
return {
child2Msg: ""
};
},
methods: {
getMag(msg) {
this.child2Msg = msg;
}
}
};
此时我在父组件里面定义了一个@toParent方法这个名称要和子组件里面this.$emit(arg1)的命名一样,用来接收。在getMag里面接收一个参数就是当前传回的值。
效果
没传值的时候.png
已经传值.png
3.兄弟组件传值
兄弟组件之间就需要一个中间值,我在这里称为bus。在vue文件main.js中,我们利用 Vue.prototype.bus=new Vue() 来定义,此时我们就有了一个中间量。
这是第一个子组件 -- 从这里向另外一个子组件传值
我是第一个子组件我要给第二个兄弟发信息,内容是:
点我给兄弟传值