在 Vue.js 中,可以使用几种方法进行组件间的通信,通常的附件和事件在大多数情况下都足够,但还有其他方法可供您使用。
Props & 事件
当然,通讯的正常方法涉及附件和事件,这种共同的模式提供了组件之间通信的强大方式,而不引入任何依赖或限制,其中组件是涉及的。
Props 允许您将任何数据类型传输给儿童组件,并允许您控制您的组件接收的数据类型。
寺庙使用:
1<my-component v-bind:prop1="parentValue"></my-component>
2<!-- Or more succinctly, -->
3<my-component :prop1="parentValue"></my-component>
此分類上一篇: https://vuejs.org/v2/api/#v-on
事件提供了一种方式来告知您的父母对儿童的变化。
寺庙使用:
1<my-component v-on:myEvent="parentHandler"></my-component>
2<!-- Or more succinctly, -->
3<my-component @myEvent="parentHandler"></my-component>
点燃一个事件:
1...
2export default {
3 methods: {
4 fireEvent() {
5 this.$emit('myEvent', eventValueOne, eventValueTwo);
6 }
7 }
8}
此外,您可以创建全球事件巴士,在您的应用程序中的任何地方播放事件。
组合:**
使用 v 模型允许将附件与事件相结合以进行双向绑定. 这种方法通常用于输入组件。
寺庙使用:
1<my-component v-model="prop1"></my-component>
V 模型兼容组件:
1<template>
2 <div>
3 <input type="text" :value="value" @input="triggerEvent"/>
4 </div>
5</template>
6
7<script>
8 export default {
9 props: {
10 value: String
11 },
12
13 methods: {
14 triggerEvent(event) {
15 this.$emit('input', event.target.value);
16 }
17 }
18 }
19</script>
** 使用时:** 您需要在组件之间进行几乎任何类型的数据传输和消息传输。
注射 / 注射
Vue 的更新的补充是 提供 / 注射机制。它允许从一个祖先组件的数据或方法选择性暴露给其所有后代。
提供 / 注入可能不是开发应用程序的好主意,但在写完整的 自定义渲染组件库时,它可以非常有用。
原始元素:
1const SomethingAllDescendantsNeed = 'Air, probably.';
2
3export default {
4 provide: {
5 SomethingAllDescendantsNeed
6 }
7}
降级组件(s):
1export default {
2 inject: ['SomethingAllDescendantsNeed'],
3
4 mounted() {
5 console.log(this.SomethingAllDescendantsNeed);
6 }
7}
寺庙使用:
1<ancestor-component>
2 <div>
3 <descendant-component>
4 <p>
5 <descendant-component></descendant-component>
6 </p>
7 </descendant-component>
8 </div>
9</ancestor-component>
(所有后代组件,无论树的深度有多深,都可访问 SomethingAllDescendantsNeed。
** 使用时:** 儿童组件需要访问每个组件树只对某些事物进行实例化一次的实例。
直接访问
警告:这里是鲨鱼!
如果你真的,真的,真的,真的,需要访问一个属性或方法,直接在一个父母或孩子组件,你可以使用每个组件的 this.$parent 和 this.$children 属性,有充分的访问所有关于父母和孩子组件。
使用時: 使用時: 使用時: 使用時: 使用時:
为什么不呢?因为你正在引入父母和孩子组件之间的实现和标记结构之间的直接结合,使它们不灵活,易于破坏。