vue 跨组件传值(学习)

本文介绍了如何使用Vue的EventBus实现跨组件通信。通过创建一个空白的Vue实例作为事件总线,并在需要发送或接收数据的组件中进行相应操作,实现了组件间的值传递。
摘要由CSDN通过智能技术生成

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

259-aaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值