一、组件之间的关系
在实际开发中,组件最常见的关系分为父子关系,兄弟关系
二、组件之间的数据共享
2.1、父组件向子组件
父组件向子组件共享数据需要使用自定义属性。示例代码如下
<!-- 父组件 -->
<Left :msg="message" :user="userinfo"></Left>
子组件使用props进行接受,示例代码:
props: {
msg: {},
user: {},
},
2.2、子组件向父组件共享数据
子组件向父组件共享数据需要使用自定义事件,示例代码如下
子组件:
this.$emit("num", this.count);
// num为自定义事件,实参为count
父组件:
<Right @num="newcount"></Right>
// 定义num自定义事件,调用newCount函数
methods:{
newcount(val){
this.countSon = val
// 将传来的实参复制给countSon
}
},
2.3、兄弟组件之间数据共享
在vue2.x中兄弟组件共享数据使用的是EventBus
EventBus的使用步骤
- 创建 eventBus.js 模块,并向外共享一个 Vue 的实例对象
- 在数据发送方,调用 bus.$emit('事件名称', 要发送的数据) 方法触发自定义事件
- 在数据接收方,调用 bus.$on('事件名称', 事件处理函数) 方法注册一个自定义事件
示例代码:
发送方:
import bus from "@/components/enevtBus.js";
methods: {
send() {
// 通过eventbug发送数据
bus.$emit("share", this.str);
},
},
接收方:
import bus from "@/components/enevtBus.js";
created() {
// 获取left组件传过来的str
bus.$on("share", (val) => {
this.strFromLeft = val;
});
},
eventbus:
import Vue from 'vue'
export default new Vue()
Comments | 2 条评论
上面第一个例子props如果没有对参数进行限制的话其实可以写成 props: [‘msg’, ‘userInfo’] 会更简单一点,当然如果需要定义初始值或者类型之类的就要传入Object了,例如https://v3.cn.vuejs.org/guide/component-props.html#props
当然这个类型好像会在编译的时候进行检测,实际运行起来如果传递的不对也可能可以正常运行,就像TypeScript
@橙梓 ::BZ:re_miao:: 妙啊