父组件:
<template>
<div>
<son :msg="message" :user="userinfo">son>
div>
template>
<script>
import son from "./son.vue";
export default {
components: { son },
data() {
return {
message: "hello vue.js",
userinfo: {
name: "张无忌",
age: 25,
},
};
},
};
script>
<style>
style>
子组件:
<template>
<div>
<h5>Son组件h5>
<p>父组件传过来的 msg 值时:{{ msg }}p>
<p>父组件传过来的 user 值时:{{ user }}p>
div>
template>
<script>
export default {
props: ["msg", "user"],
};
script>
<style>
style>
父组件:
<template>
<div class="fatherContainer">
<p>父组件中countFromSon的值:{{ countFromSon }}p>
<son @numchange="getNewCount">son>
div>
template>
<script>
import son from "@/components/son.vue";
export default {
components: {
son,
},
data() {
return {
countFromSon: 0,
};
},
methods: {
getNewCount(val) {
this.countFromSon = val;
},
},
};
script>
<style lang="less" scoped>
.fatherContainer {
background-color: springgreen;
}
style>
子组件:
<template>
<div class="sonContainer">
<p>count的值是:{{ count }}p>
<p>{{ person }}p>
<button @click="add">+1button>
div>
template>
<script>
export default {
data() {
return {
count: 0,
person: {
name: "张无忌",
age: 24,
},
};
},
methods: {
add() {
this.count++;
// 修改数据时,通过$emit()触发自定义事件
this.$emit("numchange", this.count);
},
},
};
script>
<style lang="less">
.sonContainer {
background-color: peru;
}
style>
eventBus.js 模块:
import Vue from 'vue'
// 向外共享Vue的实例对象
export default new Vue()
发送方:
<template>
<div class="fatherContainer">
父亲组件
<p>
父组件中 msg 的值:<b>{{ msg }}b>
p>
<button @click="sendMsg">发送数据button>
div>
template>
<script>
import bus from "@/eventBus.js";
import son from "@/components/son.vue";
export default {
components: {
son,
},
data() {
return {
msg: "为中华崛起而读书!!!",
};
},
methods: {
sendMsg() {
bus.$emit("share", this.msg);
},
},
};
script>
<style lang="less" scoped>
.fatherContainer {
background-color: springgreen;
}
style>
接收方:
<template>
<div class="matherContainer">
母亲组件
<p>父亲组件传过来的值是:{{ msgFromFather }}p>
div>
template>
<script>
import bus from "@/eventBus.js";
export default {
data() {
return {
msgFromFather: "",
};
},
created() {
bus.$on("share", (val) => {
this.msgFromFather = val;
});
},
};
script>
<style lang="less">
.matherContainer {
background-color: tomato;
}
style>