1.父组件向子组件传值
parent.vue
<template>
<div>
<Child :msg="11" :fn="fn" />
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
name: "parent",
components: {
Child,
},
methods: {
fn(data) {
console.log("子组件调用传过来的数据", data);
},
},
};
</script>
<style lang="scss" scoped></style>
child.vue
<template>
<div>
<h1>父组件传过来的值msg:{{ msg }}</h1>
</div>
</template>
<script>
export default {
props: ["msg", "fn"],
mounted() {
this.fn({ name: "lisi" });
},
};
</script>
<style lang="scss" scoped></style>
2.子组件向父组件传值
parent.vue
<template>
<div>
<Child @fn="handleClick" />
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
name: "parent",
components: {
Child,
},
methods: {
handleClick(data) {
console.log("子组件传过来的数据", data);
},
},
};
</script>
<style lang="scss" scoped></style>
child.vue
<template>
<div>
<button @click="handleClick">点击我向父组件传值</button>
</div>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit("fn", 123);
},
},
};
</script>
<style lang="scss" scoped></style>
3.消息发布与订阅-pubsub-js
用于任意组件通信
npm i pubsub-js -S
parent.vue
<template>
<div>
<Child />
</div>
</template>
<script>
import Child from "./Child.vue";
import pubSub from "pubsub-js";
export default {
name: "parent",
components: {
Child,
},
mounted() {
//订阅消息取数据
pubSub.subscribe("one", (a, b) => {
//参数一是事件名 参数二是传递过来的数据
console.log("a", a);
console.log("b", b);
});
},
};
</script>
<style lang="scss" scoped></style>
child.vue
<template>
<div>
<button @click="handleClick">点击我向父组件传值</button>
</div>
</template>
<script>
import pubSub from "pubsub-js";
export default {
methods: {
handleClick() {
//发布消息,传递数据
pubSub.publish('one',123)
},
},
};
</script>
<style lang="scss" scoped></style>
4.全局事件总线
注意:最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
main.js注册
import Vue from 'vue'
import App from './App.vue'
// 关闭vue的生产提示
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
// 安装全局事件总线
beforeCreate() {
// $bus相当于一个事件中心
Vue.prototype.$bus = this
}
}).$mount('#app')
提供数据
<template>
<div class="styl">
<button @click="sendMsg">发送数据</button>
</div>
</template>
<script>
export default {
methods: {
sendMsg() {
// 发送数据
// 通过$emit触发send事件,发送this.name数据
this.$bus.$emit("send", 数据);
},
},
};
</script>
接收数据
<script>
export default {
name: "School",
methods: {
//getMsg回调函数 接收组件传过来的数据
getMsg(data) {
console.log('data',data)
},
},
//挂载期: 自动接收
mounted() {
// 绑定自定义事件send,getMsg作为回调函数接收数据
this.$bus.$on("send", this.getMsg);
},
};
</script>