vue组件的8中传值方式

今天我介绍一下vue的8种传值方式:


image.png

这里我们只介绍:

  • children/parent
  • provide/inject
  • EventBus
  • attrs/listeners

children/parent

注意:vue3以后没有$children了

  1. 组件
<template>
  <div class="view">
    <div  @click="changeParent">{{ name }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "前端开发攻城狮",
      list: [],
    };
  },
  mounted() {
    console.log("父类", this.$parent);
  },
  methods:{
    changeParent(){
      this.$parent.nick = '参见Vue叔叔'
    }
  }
};
</script>
  1. 父类
<template>
  <div>
    <div>你好,Vue。</div>
    <test></test>
    <div>{{ nick }}</div>
  </div>
</template>

<script>
import test from "./views/component";
export default {
  name: "App",
  components: {
    test
  },
  data() {
    return {
      nick: "",
    };
  },
  mounted() {
    console.log("子类", this.$children);
    this.$children. name = '前端开发深似海'
  },
};
</script>

provide/inject

1.组件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
    abc: String
  },
  inject: ["self", "param", "clickFuntion"], // "abc" 获取不到,因为props中已经定义了。
  mounted() {
    console.log("inject param:", this.$options.inject);
    this.$options.inject.forEach(e=>console.log(`key: ${e} __ `,this[e]));
    this.clickFuntion(this); // 执行改函数
  }
};
</script>

2.父类

<template>
  <div class="view">
    <HelloWorld :msg="name" />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
var list = [1, 2, 3];
export default {
  name: "App",
  components: {
    HelloWorld
  },
  data() {
    return {
      nick: "前端开发攻城狮",
      name: "阳光派小伙",
      dsdasd: "ddddddd"
    };
  },
  computed: {
    getList() {
      return list;
    }
  },
  provide: {
    self: this,
    param: list,
    abc: '1234',
    clickFuntion: (children)=>{
      console.log('父类里面:',children.msg ?? '执行某些事情');
    }
  },
  methods: {
    getdata() {
      this.name = "阳光派小伙,小军";
    }
  }
};
</script>

注意: provide 可以透传多个层级,实现儿子与祖父的传值调用

EventBus(可用于一对多传值)

  • 创建EventsBus单例
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
  • 子组件/孙子组件/兄弟组件 来接收通知
<template>
  <div>计算和: {{count}}</div>
</template>

<script>
import { EventBus } from './event-bus.js'
export default {
  data() {
    return {
      count: 0
    }
  },

  mounted() {
    EventBus.$on('addition', param => {
      this.count = this.count + param.num;
    })
  }
}
</script>
  • 发送通知
<template>
  <div>
    <button @click="additionHandle">+加法器</button>    
  </div>
</template>

<script>
import {EventBus} from './event-bus.js'
console.log(EventBus)
export default {
  data(){
    return{
      num:1
    }
  },

  methods:{
    additionHandle(){
      EventBus.$emit('addition', {
        num:this.num++
      })
    }
  }
}
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容