vue中组件通讯方法,看看有没有不知道的

122 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第32天,点击查看活动详情

一、组件通信方式表

2、2022年前端技术梳理篇《Vue组件间通信》

2、2022年前端技术梳理篇《Vue组件间通信》

二、组件通信演示

1. props

  • 父组件定义数据代码:
<Child :msg="data"/>

data() {
  return {
    data: 'Welcome to Your Vue.js App'
  }
}
  • 子组件定义props接收数据代码
<h1>{{ msg }}</h1>

props: {
  msg: {
    type: String,
      default: ''
  },
}

2. emit&$on

  • 子组件派发事件代码
<button @click="sendDataToParent">发送</button>

methods: {
  sendDataToParent() {
    this.$emit("send", "我是子组件");
  },
}
  • 父组件绑定事件代码v1
<Child @send="childSend($event)" />

methods: {
  childSend(value) {
    console.log('value :>> ', value);
  }
}
  • 父组件绑定事件代码v2
<Child ref="child1" />

mounted() {
 this.$refs.child1.$on("send", (value) => {
   console.log("parent received value is :>> ", value);
 });
}

3. eventbus

  • 自定义bus代码:
/* eslint-disable no-unused-vars */
class Bus {
    constructor() {
        this.callbacks = {}
    }

    on(name, fn) {
        this.callbacks[name] = this.callbacks[name] || []
        this.callbacks[name].push(fn)
    }

    emit(name,args){
        if(this.callbacks[name]){
            this.callbacks[name].forEach(callback => {
                callback(args)
            });
        }
    }
}
module.exports = Bus
  • 子组件1发送数据代码:
<button @click="send">发送</button>

<script>
export default {
  name: "Child",
  methods: {
    send() {
      this.$bus.emit("send", "我是子组件1");
    },
  },
};
</script>
  • 子组件2接收数据代码:
export default {
  name: "Child2",
  mounted() {
    this.$bus.on("send", (value) => {
      console.log("value :>> ", value);
    });
  },
};
  • 公共父组件代码:
<template>
  <div>
    <Child />
    <Child2 />
  </div>
</template>

4. $refs

  • 父组件调用子组件函数/设置数据/获取数据代码:
<Child ref="child1" />

mounted() {
  // ** 注意组件挂载顺序
  // 获取子组件data数据
  console.log("this.$refs.child1.msg :>> ", this.$refs.child1.msg);
  // 修改子组件data数据
  this.$refs.child1.msg = "parent modify data";
  // 调用子组件函数
  this.$refs.child1.console("hello");
}
  • 子组件代码:
<template>
  <div ref="c1" class="hello">
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: "Child",
  data() {
    return {
      msg: "I'm child.",
    };
  },
  mounted() {
    console.log("child msg :>> ", this.msg);
  },
  methods: {
    console(value) {
      console.log("parent value is :>> ", value);
    },
  },
};
</script>

5. $parent

  • 子组件1通过$parent发送数据代码:
<button @click="sendDataToChild2">发送</button>

methods: {
  sendDataToChild2() {
    this.$parent.$emit("send", "我是子组件1");
  },
}
  • 子组件2通过$parent接收数据代码:
mounted () {
  this.$parent.$on('send',(value)=>{
    console.log('child2 received value is :>> ', value);
  })
}
  • 公共父组件代码:
<template>
  <div ref="app">
    <Child />
    <Child2 />
  </div>
</template>

6. $children

  • 父组件调用子组件函数/设置数据/获取数据代码:
<Child ref="child1" />

mounted () {
  console.log('this.$children :>> ', this.$children);
  const children = this.$children[0]
  if(children.$vnode.data.ref === "child1"){
    console.log('children.msg :>> ', children.msg);
    children.message('hello')
  }
}
  • 子组件代码:
<template>
  <div ref="c1" class="hello">
  </div>
</template>

<script>
export default {
  name: "Child",
  data() {
    return {
      msg: "hello vue",
    };
  },
  methods: {
    message(value) {
      console.log("value :>> ", value);
    },
  },
};
</script>

7.root(root(同parent)

// 发送修改为
this.$root.$emit("send", "我是子组件1");

// 接收修改为
this.$root.$on('send',(value)=>{
  console.log('child2 received value is :>> ', value);
})

8. provide&inject

  • 父组件设置provide代码
<Child />

export default {
  provide() {
    return { msg: "hello vue" };
  },
  components: {
    Child,
  },
};
  • 子组件配置孙辈组件代码
<Grandson></Grandson>

export default {
  components: {
    Grandson,
  },
};
  • 孙辈组件通过inject获取数据代码
export default {
    inject: ['msg'],
};

9. $attrs属性传参

案例1(父=>子传参):

    1. 父组件传递数据代码:
<Child value="Hello Vue" />
    1. 子组件接收数据代码:
<!--非属性特性-为在props中定义-->
<div>{{$attrs.value}}</div>

案例2(父=>孙传参,子桥接):

    1. 父组件传递数据代码:
<Child value="Hello Vue" />
    1. 子组件桥接属性代码:
<!--非属性特性-为在props中定义-->
<!--利用$attrs展开语法跨层级多参数传递-->
<Grandson v-bind="$attrs"></Grandson>
    1. 孙辈组件通过props属性接收数据代码:
<div>{{ value }}</div>

props: {
  value: {
    type: String,
    default: "",
  },
},

10. $listeners事件传参

案例1(子=>父传参)

    1. 子组件派发事件代码:
<button @click="send">发送</button>

send() {
  this.$listeners.event('hello vue')
}
    1. 父组件绑定事件接收数据代码:
<Child @event="message" />
  
message(value) {
  console.log('value :>> ', value);
}

案例2(孙=>父传参,子桥接)

    1. 孙辈组件派发事件代码:
<button @click="send">发送</button>

this.$emit("event", "hello vue");
    1. 子组件桥接事件代码:
<!--利用$listeners展开语法跨层级多参数传递-->
<Grandson v-on="$listeners"></Grandson>
    1. 父组件绑定事件接收数据代码:
<Child @event="message" />
  
message(value) {
  console.log('value :>> ', value);
}