vue component 跨组件传值(学习)

跨组件通信(EventBus)

两个vue组件没有引入关系

效果

在这里插入图片描述

主要代码

  1. src/EventBus/index.js - 创建空白Vue对象并导出
    空白Vue对象 – 监听和触发事件
import Vue from 'vue'
// 导出空白vue对象
export default new Vue()

在这里插入图片描述

  1. 在要接收值的组件(List.vue)

eventBus.$on('事件名',函数体)

<template>
  <ul class="my-product">
    <li v-for="(item, index) in arr" :key="index">
      <span>{{ item.proname }}</span>
      <span>{{ item.proprice }}</span>
    </li>
  </ul>
</template>

<script>
// 目标: 跨组件传值
// 1. 引入空白vue对象(EventBus)
// 2. 接收方 - $on监听事件
import eventBus from "../EventBus";
export default {
  props: ["arr"],
  // 3. 组件创建完毕, 监听send事件
  created() {
    eventBus.$on("send", (index, price) => {
      this.arr[index].proprice > 1 &&
        (this.arr[index].proprice = (this.arr[index].proprice - price).toFixed(2));
    });
  },
};
</script>
  1. 在要传递值的组件(MyProduct.vue)
    eventBus.$emit('事件名',值)
<template>
  <div class="my-product">
    <h3>标题: {{ title }}</h3>
    <p>价格: {{ price }}</p>
    <p>{{ intro }}</p>
    <button @click="subFn">宝刀-1</button>
  </div>
</template>

<script>
import eventBus from '../EventBus'
export default {
  props: ['index', 'title', 'price', 'intro'],
  methods: {
    subFn(){
      eventBus.$emit("send", this.index, 1) // 跨组件
    }
  }
}
</script>
  1. 展示(App.vue)
<template>
  <div style="overflow: hidden;">
    <div style="float: left;">
      <MyProduct
      v-for="(obj, ind) in list"
      :key="obj.id"
      :title="obj.proname"
      :price="obj.proprice"
      :intro="obj.info"
      :index="ind"
      @subprice="fn"
    ></MyProduct>
    </div>
    <div style="float: left;">
      <List :arr="list"></List>
    </div>
  </div>
</template>

<script>
import MyProduct from "./components/MyProduct_sub";
import List from "./components/List";
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          proname: "超级好吃的棒棒糖",
          proprice: 18.8,
          info: "开业大酬宾, 全场8折",
        },
        {
          id: 2,
          proname: "超级好吃的大鸡腿",
          proprice: 34.2,
          info: "好吃不腻, 快来买啊",
        },
        {
          id: 3,
          proname: "超级无敌的冰激凌",
          proprice: 14.2,
          info: "炎热的夏天, 来个冰激凌了",
        },
      ],
    };
  },
  components: {
    MyProduct,
    List,
  },
  methods: {
    fn(inde, price) {
      this.list[inde].proprice > 1 &&
        (this.list[inde].proprice = (this.list[inde].proprice - price).toFixed(
          2
        ));
    },
  },
};
</script>

版权声明:本文为qq_44680550原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。