vue中是怎么实现父向子、子向父、兄弟之间的传值的?

180 阅读1分钟

父向子传值

一、通过的是props属性来传值,props只读

父代码:

<template>
  <div>
    <input type="text" v-model="val">
    <childA :toChildVal="val" style="margin-top:20px"></childA>
  </div>
</template>
<script>
import childA from "@/components/childA";
export default {
  name: "parent",
  components: {
    childA,
  },
  data() {
    return {
      val: "",
    };
  },
};
</script>
<style lang="">
</style>

子代码:

<template>
  <div>
    {{toChildVal}}
  </div>
</template>
<script>
export default {
  name: "childA",
  props: {
    toChildVal: {
      //对象形式接收  =>推荐使用此方式,直接可以通过this.toChildVal取值
      type: String, //设置数据类型
      default: "", //数据默认值
    },
  },
};
</script>
<style lang="">
</style>

二、ref属性与refs
在Vue中一般很少会用到直接操作DOM,但是不可以避免有时候需要用到,因此这时我们可以通过ref和$refs来实现。

ref
预期类型:string
ref被用来给元素或子组件注册引用消息,引用消息将会注册在父组件的$ref对象上。

  • 如果是在普通的DOM元素上使用,引用指向的就是DOM元素
  • 如果用在子组件上,引用就是指向组件实例:
<child-component ref="child"></child-component>

$refs

$refs是一个对象,持有已经注册过的ref的所有组件

注意:refs指挥在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——应该要避免在模板或者计算属性中访问refs指挥在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——**应该要避免在模板或者计算属性中访问refs**

<div>
new Vue({
        el:"#id",
        components:{
           child-component
        },
        created() {
        let this=_this
        //像子组件的方法进行传参
            _this.$refs.child.setChildMethods('123')
            }
        }
    });

兄弟组件传值 事件总线 EventBus

在Vue中可以使用EventBus来作为沟通桥梁的概念,就像是所有组件共同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知去其他组件,但是也就是太方便所以若时间不慎,就会造成难以维护的“灾难”,因此需要更完善的Vuex作为状态管理中心,将通知的概念上升等到共享状态层次。
实质上,Eventbus是一个不具备Dom组件,它具有的仅仅只是它的实例方法而已,因此它非常地轻便。

局部EventBus

一、初始化
①创建一个event-bus.js文件,创建事件总线并将其导出,以便其它模块可以使用或者监听。

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

②直接在main.js初始化EventBus:

// main.js
Vue.prototype.$EventBus = new Vue()

二、发送事件 EventBus.$emit

<!-- A.vue -->
<template>
    <button @click="sendMsg()">-</button>
</template>

<script> 
import { EventBus } from "../event-bus.js";
export default {
  methods: {
    sendMsg() {
      EventBus.$emit("aMsg", '来自A页面的消息');
    }
  }
}; 
</script>

三、接收事件 EventBus.$on

<!-- IncrementCount.vue -->
<template>
  <p>{{msg}}</p>
</template>

<script> 
import { 
  EventBus 
} from "../event-bus.js";
export default {
  data(){
    return {
      msg: ''
    }
  },
  mounted() {
    EventBus.$on("aMsg", (msg) => {
      // A发送来的消息
      this.msg = msg;
    });
  }
};
</script>

四、移除事件监听者 EventBus.$off

import { 
  eventBus 
} from './event-bus.js'
EventBus.$off('aMsg', {})

全局EventBus

它的工作原理是发布/订阅的方式,同称为Pub/Bus
一、创建全局EventBus

var EventBus = new Vue();

Object.defineProperties(Vue.prototype, {
  $bus: {
    get: function () {
      return EventBus
    }
  }
})

二、发布emit、订阅emit、订阅on

var EventBus = new Vue();

this.$bus.$emit('nameOfEvent', { ... pass some event data ...});

this.$bus.$on('nameOfEvent',($event) => {
  // ...
})

三、移除事件监听
this.$bus.$off('sendMsg')