关于Vue的组件通信
我们需要知道的是什么是组件,什么是组件通信,怎么使用?
1.什么是组件?
我认为组件是和vuex有一丝相处的地方的一种东西。
相似的地方在于:两者都可供多个页面使用
不同的地方在于:组件里面可以书写布局,而vuex只能存放数据
2.什么是组件通信?
组件通信顾名思义,就是组件与组件中的联系,也就是组件通信。
因为组件可以说是一个具有独立功能的整体,当我们要将这些组件拼接在一起时,这些组件互相之间要建立联系,这个在组件中进行的联系我们就称之为组件通信。
我们常用的组件通信有是三种,父传子( 用props来实现),子传父(用自定义事件实现),还有兄弟组件传值($bus)。
1.父传子
父组件:
<template>
<div class="worry">
<child :inputValue = 'value'></child>
</div>
</template>
<script>
//引入子组件
import child from '../components/child'
export default {
data () {
return {
value:'父组件的value'
}
},
components:{
child
}
}
</script>
子组件:
<template>
<div class="child">
{{inputValue}}
</div>
</template>
<script>
export default {
//接受父组件传的值
props:{
inputValue:String
}
}
</script>
父组件传值成功
props 可以是基础数据或对象,用于接收来自父组件的数据。
1.数组
props: ['size', 'myMessage'] //不限制数据类型
2.对象
props: {
inputValue: String //指定了字符串类型,如果类型不一致会警告
}
//或
props: {
//数组写法
inputValue: {
type: String,
default: ''
}
}
1.props与data同级,用于父传子
2.props传值是单向的
2.子传父
比起父传子,子传父就要简单的多
父组件:
<template>
<Input @input="input"/>
</template>
<script>
//引入组件
import Input from '../components/Input.vue'
export default {
data() {
return {
value:'',
};
},
mounted() {},
methods: {
input(i) {
this.value = i;
},
},
components:{
Input
}
};
</script>
<style lang='scss' scoped>
</style>
子组件:
<template>
<div class='div'>
<input
type="text"
v-model="aa"
@input="input"
>
</div>
</template>
<script>
export default {
data() {
return {
aa:''
};
},
mounted() {},
methods: {
//自定义事件传值
input(){
this.$emit("input",this.aa)
}
},
};
</script>
<style lang='scss' scoped>
.div {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
// padding: 10px 0;
box-sizing: border-box;
}
input {
width: 80vw;
height: 50px;
padding: 0 2%;
box-sizing: border-box;
margin-top: 30px;
}
</style>
3.非父子传值
1. 初始化,全局创建$bus
直接在项目中的 main.js 初始化 $bus :
window.$bus=new Vue();
2. 发送事件
A发送消息到B
<!-- A.vue -->
<template>
<button @click="aa()">-</button>
</template>
<script>
export default {
methods: {
aa() {
$bus.$emit("a", 'A的消息');
}
}
};
</script>
B接收A
<!-- B.vue -->
<template>
<p>{{msg}}</p>
</template>
<script>
export default {
data(){
return {
msg: ''
}
},
mounted() {
$bus.$on("a", (msg) => {
// A发送来的消息
this.msg = msg;
});
}
};
</script>