非父子组件的通信
Provide和Inject
Provide和Inject基本使用
Provide和Inject函数的写法
处理响应式数据
A pp.vue
<template>
<div>
<home></home>
<button @click="addName">+name</button>
</div>
</template>
<script>
import Home from "./Home.vue";
import { computed } from "vue";
export default {
components: {
Home,
},
// 为了使用this。,写成函数
provide() {
return {
name: "why",
age: 18,
// this.names.length:一次性赋值,不会改变
// computed:变成响应式
length: computed(() => this.names.length), // ref对象 .value
};
},
data() {
return {
names: ["abc", "cba", "nba"],
};
},
methods: {
addName() {
this.names.push("why");
console.log(this.names);
},
},
};
</script>
<style scoped></style>
Home.vue
<template>
<div>
<home-content></home-content>
</div>
</template>
<script>
import HomeContent from "./HomeContent.vue";
export default {
components: {
HomeContent,
},
};
</script>
<style scoped></style>
HomeContent.vue
<template>
<div>HomeContent: {{ name }} - {{ age }} - {{ length.value }}</div>
</template>
<script>
export default {
inject: ["name", "age", "length"],
};
</script>
<style scoped></style>
全局事件总线mitt库
使用事件总线工具
Mitt的事件取消
eventbus.js
import mitt from 'mitt';
const emitter = mitt();
// export const emitter1 = mitt();
// export const emitter2 = mitt();
// export const emitter3 = mitt();
export default emitter;
App.vue
<template>
<div>
<home />
<about />
</div>
</template>
<script>
import Home from "./Home.vue";
import About from "./About.vue";
export default {
components: {
Home,
About,
},
};
</script>
<style scoped></style>
HomeContent.vue
<template>
<div></div>
</template>
<script>
import emitter from "./utils/eventbus";
export default {
created() {
emitter.on("why", (info) => {
console.log("why:", info);
});
emitter.on("kobe", (info) => {
console.log("kobe:", info);
});
emitter.on("*", (type, info) => {
console.log("* listener:", type, info);
});
},
};
</script>
<style scoped></style>
About.vue
<template>
<div>
<button @click="btnClick">按钮点击</button>
</div>
</template>
<script>
import emitter from "./utils/eventbus";
export default {
methods: {
btnClick() {
console.log("about按钮的点击");
emitter.emit("why", { name: "why", age: 18 });
// emitter.emit("kobe", {name: "kobe", age: 30});
},
},
};
</script>
<style scoped></style>