1.Vue组件之间传值问题
转自: https://blog.csdn.net/lzb348110175/article/details/88880538
1、父组件传值给子组件------->使用props属性接收
2、子组件传值给父组件-------->子组件通过$emit传递,父组件通过@属性名称接收
3、父组件,子组件,兄弟组件相互传值------>需要bus中央总线,相当于一个中介
1、父组件传值给子组件------->使用props属性接收
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<my-component :message="message"></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<span>|||我接收的值是|||:{{message}}</span>',
props: {
message: {
type: String
}
}
});
var app = new Vue({
el: '#app',
data: {
message:'我是父组件要传给子组件的值'
}
});
</script>
</body>
</html>
2、子组件传值给父组件-------->子组件通过$emit传递,父组件通过@属性名称接收
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
//2.父组件通过@来接受,然后通过getMsg方法来处理数据
<my-component @message="getMsg"></my-component><br>
<span>{{message}}</span>
</div>
<script>
Vue.component('my-component',{
template:'<button @click="sendData">向父组件传值</button>',
methods:{
sendData:function (e) {
//1.子组件通过this.$emit(key,value)传递值给父组件
this.$emit('message','我是子组件要传递给父组件的值');
}
}
});
var app = new Vue({
el: '#app',
data: {
message:'1'
},
methods: {//4、此处必须是methods,不能是计算属性,mounted等
//3.处理数据
getMsg:function (msg) {
this.message = msg;
}
}
});
</script>
</body>
</html>
3、父组件,子组件,兄弟组件相互传值------>需要bus中央总线,相当于一个中介
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{message}}
<my-component></my-component>
<my-component1></my-component1>
</div>
<script>
//定义中央总线bus
var bus = new Vue();
//组件1
Vue.component('my-component',{
template:'<button @click="btnClick">click</button>',
methods:{
btnClick:function () {
//通过bus中央总线传值,使用bus.$emit(key,value);
bus.$emit('data',111111)
}
}
})
//组件2
Vue.component('my-component1',{
data:function(){
return {
msg:'第二个组件'
}
},
template:'<span>{{msg}}</span>',
//兄弟组件:通过bus中央总线接收值,使用bus.$on(key,function(){...});
//此处需要使用钩子函数:mounted
mounted:function () {
var _this = this; //此处注意this指向
bus.$on('data',function (msg1) {
alert(msg1)
_this.msg = msg1;
})
}
})
var app = new Vue({
el: '#app',
data:{
message:'this is message'
},
//父组件:通过bus中央总线接收值,使用bus.$on(key,function(){...});
//此处需要使用钩子函数:mounted
mounted: function () {
var _this = this;
bus.$on('data',function (msg) {
_this.message = msg
})
}
})
</script>
</body>
</html>
网友评论