Vue 提供了各种各样的通讯,其中包括兄弟间的通讯和非兄弟间的通讯,借此机会做个总结,查阅起来方便。

1、props

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1

代码结构

在父亲组件中使用儿子组件,给儿子通过==:date="xxx"==单向传值

<template>
  <div>
    <div>爸爸:{{date}}</div>
    <Son1 :date="date"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      date: 1,
    };
  },
};
</script>

儿子组件通过==props==接受父组件传过来的值

<template>
  <div>儿子:{{date}}</div>
</template>
<script>
export default {
  props: {
    date: {
      type: Number, //校验类型
      default: "1",
    },
  },
};
</script>

2、$emit

结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1

代码结构

子组件通过触自身的方法来触发==$emit==方法,再触发父组件的方法,通过==回调传参==的方式将修改的内容传递给父组件

<template>
  <div>
    <div>儿子:{{date}}</div>
    <button @click="changeNum">修改</button>
  </div>
</template>
<script>
export default {
  props: {
    date: {
      type: Number,
      default: "1",
    },
  },
  methods: {
    changeNum() {
      this.$emit("changeNum", 2);
    },
  },
};
</script>

父组件接受回调==params==参数,即爸爸需要给儿子绑定了一个自定义的事件,==$on("changeNum",params)==

<template>
  <div>
    <div>爸爸:{{date}}</div>
    <Son1 :date="date" @changeNum="changeNum"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      date: 1,
    };
  },
  methods: {
    changeNum(params) {
      this.date = params;
    },
  },
};
</script>

.sync

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1

代码结构

子组件通过==$emit("update:xxx")==发射事件

<template>
  <div>
    <div>儿子:{{date}}</div>
    <button @click="changeNum">修改</button>
  </div>
</template>
<script>
export default {
  props: {
    date: {
      type: Number,
      default: "1",
    },
  },
  methods: {
    changeNum() {
      this.$emit("update:date", 2);
    },
  },
};
</script>

父组件通过==:xxx.sync="xxx"==接受参数

<template>
  <div>
    <div>爸爸:{{date}}</div>
    <Son1 :date.sync="date"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      date: 1,
    };
  },
};
</script>
<Son1 :date.sync="date"></Son1>
//这个写法是上面的替代品 默认组件内部触发 update:count 规定写法
<Son1 :date="date" @update:date="val=>date=val"></Son1>

v-model

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1

代码结构

子组件触发的事件只能是==input==事件,接收==props==的属性名只能叫==value==

<template>
  <div>
    <div>儿子:{{value}}</div>
    <button @click="changeNum">修改</button>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1,
    },
  },
  methods: {
    changeNum() {
      this.$emit("input", 2);
    },
  },
};
</script>

父组件通过==v-model==接收参数

<template>
  <div>
    <div>爸爸:{{value}}</div>
    <Son1 v-model="value"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      value: 1,
    };
  },
};
</script>
<Son1 :value="value" @input="val=>value=val"></Son1>
//这个写法是上面的替代品 默认组件内部触发 input 规定写法
<Son1 v-model="value"></Son1>
v-model 局限只能传递一个属性 如果只有一个 可以使用v-model 多个依然需要使用.sync

3、$parent和 $children

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1
   ├── Grandson1.vue  //孙子1

代码结构

如下场景:孙子想要给爷爷传递数据,孙子需要找到爷爷身上的事件去传递==$parent.$emit==

<template>
  <div>
    <div>孙子{{value}}</div>
    <button @click="$parent.$emit('change',3)">修改</button>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: Number,
      default: "",
    },
  },
};
</script>

儿子组件使用孙子组件

<template>
  <div>
    <div>儿子:{{value}}</div>
    <grandson1 :value="value"></grandson1>
  </div>
</template>
<script>
import grandson1 from "./grandson1";
export default {
  components: {
    grandson1,
  },
  props: {
    value: {
      type: Number,
      default: 1,
    },
  },
};
</script>

爸爸身上给孙子自定义==change==事件

<template>
  <div>
    <div>爸爸:{{value}}</div>
    <Son1 @change="val=>value=val" :value="value"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      value: 1,
    };
  },
};
</script>
如果层级很深那么就会出现==$parent.$parent.....==我们可以封装一个==$dispatch==方法向上进行派发
Vue.prototype.$dispatch = function $dispatch(eventName, data) {
  let parent = this.$parent;
  while (parent) {
    parent.$emit(eventName, data);
    parent = parent.$parent;
  }
};
相同的道理,如果既然能够向上寻找父亲,就能向下寻找儿子,也可以封装一个向下派发的方法==$broadcast==
Vue.prototype.$broadcast = function $broadcast(eventName, data) {
  const broadcast = function () {
    this.$children.forEach((child) => {
      child.$emit(eventName, data);
      if (child.$children) {
        $broadcast.call(child, eventName, data);
      }
    });
  };
  broadcast.call(this, eventName, data);
};

4、$attrs和 $listeners

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1
   ├── Grandson1.vue  //孙子1

代码结构

==$attrs==批量向下传入属性

<template>
  <div>
    <div>爸爸:{{value}}</div>
    <Son1 @change="val=>value=val" :value="value"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      value: 1,
    };
  },
};
</script>

在儿子组件中使用 $attrs属性,配合==v-bind==可以将属性继续向下传递

<template>
  <div>
    <div>儿子:{{$attrs.value}}</div>
    <grandson1 v-bind="$attrs"></grandson1>
  </div>
</template>
<script>
import grandson1 from "./grandson1";
export default {
  components: {
    grandson1,
  },
  mounted() {
    console.log(this.$attrs);
  },
};
</script>
注意一点:在使用 ==$attrs==的时候,如果组件中使用了==props== 就会将属性从当前 ==attrs==移除掉
在孙子组件中使用 $attrs属性,可以将属性继续向下传递
<template>
  <div>
    <div>孙子{{$attrs.value}}</div>
  </div>
</template>
<script>
export default {
  //props: {
  //  value: Number,
  //},
  mounted() {
    console.log(this.$attrs);
  },
};
</script>
如果爸爸传递给儿子元素, 儿子有三个属性用不到, 孙子传递给孙子,但是不想在页面上这个属性,可以设置==inheritAttrs: false==
==$listeners==批量向下传入方法
<template>
  <div>
    <div>爸爸:{{value}}</div>
    <Son1 @click="change" :value="value"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  data() {
    return {
      value: 1,
    };
  },

  methods: {
    change() {
      this.value = 2;
    },
  },
};
</script>

可以在son1组件中使用==$listeners==属性,配合==v-on==可以将方法继续向下传递

<template>
  <div>
    <div>儿子:{{$attrs.value}}</div>
    <grandson1 v-bind="$attrs" v-on="$listeners"></grandson1>
  </div>
</template>
<script>
import grandson1 from "./grandson1";
export default {
  components: {
    grandson1,
  },
  mounted() {
    console.log(this.$attrs);
    console.log(this.$listeners);
  },
};
</script>

孙子组件可以直接使用==$listeners==上的方法

<template>
  <div>
    <div>孙子{{$attrs.value}}</div>
    <button @click="$listeners.click"></button>
  </div>
</template>
<script>
export default {
  mounted() {
    console.log(this.$attrs);
    console.log(this.$listeners);
  },
};
</script>

5、Provide & Inject

目录结构

app.vue
components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1
   ├── Grandson1.vue  //孙子1

复制代码

代码结构

在父级声明一个公共数据

export default {
  provide() {
    return { vm: this };
  },
};

在子组件中可以注入原理,会将数据挂载在当前实例上

<template>
  <div>
    <div>孙子</div>
  </div>
</template>
<script>
export default {
  inject: ["vm"],
  mounted() {
    console.log(this);
  },
};
</script>

1111.png

注意事项:这个方法使用之后比较混乱,它一般不会在业务代码中使用,经常是在组件库或者多级通信,为了方便你可以使用provide。

6、ref

目录结构

components
   ├── Parent.vue   // 父亲
   ├── Son1.vue     // 儿子1

代码结构

ref获取的是真实的dom元素,如果放到组件上代表的是当前组件的实例。 父组件中可以直接获取子组件的方法或者数据。

<template>
  <div>
    <div>爸爸</div>
    <Son1 ref="son"></Son1>
  </div>
</template>
<script>
import Son1 from "./son1";
export default {
  components: { Son1 },
  mounted() {
    this.$refs.son.show();
  },
};
</script>
<template>
  <div>
    <div>儿子</div>
  </div>
</template>
<script>
export default {
  methods: {
    show() {
      console.log(1);
    },
  },
};
</script>
注意事项:ref不要重名, 但是当且仅当使用v-for的时候会导致出现数组情况

7、EventBus

目录结构

main.js
components
   ├── Grandson1.vue   // 孙子1
   ├── Son2.vue     // 儿子2

代码结构

EventBus可用于跨组件通知(不复杂的项目可以使用这种方式)

Vue.prototype.$bus = new Vue();

Grandson1组件和Son2相互通信

<template>
  <div>孙子1</div>
</template>
<script>
export default {
  mounted() {
    this.$nextTick(() => {
      this.$bus.$emit("test", "go");
    });
  },
};
</script>

这里的儿子2组件只能使用$on来触发Grandson1组件事件

<template>
  <div>儿子2</div>
</template>
<script>
export default {
  mounted() {
    this.$bus.$on("test", (data) => {
      console.log(data);
    });
  },
};
</script>

8、Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
2222.png

具体文档查阅

9、observable

==Vue.observable==可以让返回的对象响应式,返回的对象可以直接用于渲染函数和计算属性内,并且会在发生变更时触发相应的更新,可以作为一个简单的store使用

目录结构

store
   ├── index.js
components
   ├── hello.vue   //函数式组件
   ├── home.vue     

代码结构

store/index.js

import Vue from 'vue';

export const state = Vue.observable({msg:"hello world"});

export const mutation = {
    setMsg(paylod){
       state.msg = paylod
    }
}

利用计算属性,响应式的通讯 home.vue

<template>
  <div @click="handleClick">home332131{{msg}}</div>
</template>
<script>
import { state, mutation } from "@/store";
export default {
  computed:{
    msg(){
        return state.msg
    }
  },
  methods: {
    handleClick() {
      mutation.setMsg("你好,世界");
    },
  },
};
</script>

利用渲染函数,响应式通讯 home.vue

<template>
  <div>
      <hello />
  </div>
</template>
<script>
import hello from './hello'
export default {
    components:{
        hello
    },
};
</script>

hello.vue

<script>
import { state, mutation } from "@/store";
export default {
    props:{
        render:Function
    },
     render(h) {
      return h("div",{on:{click:this.handleClick}}, `${state.msg}`);
    },
    methods:{
        handleClick() {
            mutation.setMsg("你好,世界");
        },
    }
}
</script>
最后修改:2021 年 10 月 25 日
如果觉得我的文章对你有用,请随意赞赏