Vue父子组件之间通信相对比较简单,如果非父子间通信则比较麻烦,可以考虑使用vuex。

土办法

缺点:父子组件高度依赖。

父 > 子

使用ref实现。

Parent.vue
<template>
    <div>
      parent
      <br>
      <button @click="add()">child +1</button>
      <hr>
      <Child ref="c"></Child>
    </div>
</template>

<script>
  import Child from './Child';
  export default {
      name: "Parent",
      components: {
          Child
      },
      methods:{
          add(){
              this.$refs.c.num++;
          }
      }
  };
</script>
Child.vue
<template>
    <div>
      child:{{num}}
    </div>
</template>

<script>
    export default {
        name: "Child",
        data(){
            return{
                num:0
            }
        }
    };
</script>

子 > 父

使用v-bind实现。

Parent.vue
<template>
    <div>
      parent:{{num}}
      <br>
      <hr>
      <!--将自己暴露给Child-->
      <Child :parent="this"></Child>
    </div>
</template>

<script>
  import Child from './Child';
  export default {
      name: "Parent",
      components: {
          Child
      },
      data(){
          return{
              num:0
          }
      }
  };
</script>
Child.vue
<template>
    <div>
      child
      <br>
      <button @click="add()">parent +1</button>
    </div>
</template>

<script>
    export default {
        name: "Child",
        //注册父组件传参
        props:['parent'],
        methods:{
            add(){
                this.parent.num++;
            }
        }
    };
</script>

组件事件

  • $emit:发送事件
  • $on:监听事件
  • $once:监听单次事件
  • $off:移除事件
Parent.vue
<template>
    <div>
      parent
      <br>
      <button @click="add()">child +1</button>
      <hr>
      <Child ref="c"></Child>
    </div>
</template>

<script>
  import Child from './Child';
  export default {
      name: "Parent",
      components: {
          Child
      },
      methods:{
          add(){
              //给子组件发送事件、子组件可以选择是否接收
              this.$refs.c.$emit('addNum', 10);
              //移除监听事件
              this.$refs.c.$off('addNum');
          }
      }
  };
</script>
Child.vue
<template>
    <div>
      child:{{num}}
    </div>
</template>

<script>
    export default {
        name: "Child",
        data(){
            return{
                num:0
            }
        },
        mounted() {
            //监听由vm.$emit触发的事件
            this.$on('addNum', (num) => {
                this.num += num;
            });

            //只监听一次
            this.$once('addNum', (num) => {
                this.num += num;
            });
        }
    };
</script>

组件可以选择不接收事件,也不会报错,降低了依赖。

Logo

前往低代码交流专区

更多推荐