父传子:props
子传父:自定义事件($emit)
上代码:
父组件
<template>
<div>
//发送需要给子组件的数据
<Student name="李6" sex="女" age="18" :info="info" />
</div>
</template>
<script>
import Student from "./components/Student";
export default {
data() {
return {
info: ["aaa", "bbb", "ccc"],
};
},
name: "App",
components: { Student },
};
</script>
子组件
<template>
<div>
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<h2>学生年龄:{{ myAge + 1 }}</h2>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
};
},
props: ["name", "sex", "age", "info"],
};
</script>
下面是自定义事件:
子组件:
<template>
<div>
<button @click="send">点击触发自定义事件</button>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
info: ["aaa", "bbb", "ccc"],
};
},
methods: {
send() {
//子组件向父组件传递事件,第一个参数是自定义事件名,后边的参数是数据
this.$emit("access", this.info);
},
},
};
</script>
父组件:
<template>
<div>
<!-- 此处不是浏览器产生的事件对象,是我们自定义的事件。当不加括号时,会默认传递子组件通过 $emit 发射事件时添加的数据(@/v-on:) -->
<Student v-on:access="aaa" />
</div>
</template>
<script>
import Student from "./components/Student";
export default {
methods: {
aaa(info) {
console.log(info);
},
},
components: { Student },
};
</script>
注意:不能在子组件修改通过props从父级元素发送过来的数据。
还有适用于任意组件间通信的两种方式,原理相同。
全局事件总线:
先创建全局事件总线:
new Vue({
el:'#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
},
})
发送方:this. e m i t ( ′ 事 件 名 ′ , 数 据 ) 接 收 方 : t h i s . emit('事件名',数据) 接收方: this. emit(′事件名′,数据)接收方:this.on(‘事件名’,()=>{})
订阅发布模式:
npm install pubsub-js
发布方(发送方):pubsub.publish(‘事件名’,数据)
接收方 (接收方) :pubsub.subscribe(‘事件名’,()=>{})