简体   繁体   English

如何在 VueJS 中将值从一个子组件传递到另一个子组件?

[英]How to pass value from one child component to another in VueJS?

Full source code: https://github.com/tenzan/menu-ui-tw完整源代码: https : //github.com/tenzan/menu-ui-tw

Demo: https://flamboyant-euclid-6fcb57.netlify.com/演示: https : //flamboyant-euclid-6fcb57.netlify.com/

Goal:目标:

ItemsList and ItemImage are child components to Menu.vue . ItemsListItemImage的子组件来Menu.vue I need to pass the image_url from ItemsList to ItemImage , in order to change the image on right, after item on left is changed automatically on time intervals.我需要将image_urlItemsList传递给ItemImage ,以便在左侧的项目按时间间隔自动更改后更改右侧的图像。

  • Left side: component ItemsList.vue左侧:组件ItemsList.vue
  • Right side: component ItemImage.vue右侧:组件ItemImage.vue

在此处输入图片说明

Component Menu.vue has 2 child components: Component Menu.vue有 2 个子组件:

<template>
  <div>
    <!-- Two columns -->
    <div class="flex mb-4">
      <div class="w-1/2 bg-gray-400">
        <ItemsList />
      </div>
      <div class="w-1/2 bg-gray-500">
        <ItemImage></ItemImage>
      </div>
    </div>
  </div>
</template>

<script>
import ItemsList from "./ItemsList";
import ItemImage from "./ItemImage";

export default {
  components: {
    ItemsList,
    ItemImage
  }
};
</script>

ItemsList.vue:项目列表.vue:

<template>
  <div>
    <div v-for="item in menuItems" :key="item.name">
      <ul
        class="flex justify-between bg-gray-200"
        :class="item.highlight ? 'highlight' : ''"
      >
        <p class="px-4 py-2 m-2">
          {{ item.name }}
        </p>
        <p class="px-4 py-2 m-2">
          {{ item.price }}
        </p>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menuItems: [
        {
          name: "Apple",
          price: 20,
          image_url: "../assets/images/apple.jpg"
        },
        {
          name: "Orange",
          price: 21,
          image_url: "../assets/images/orange.jpg"
        },
        {
          name: "Banana",
          price: 22,
          image_url: "../assets/images/banana.jpg"
        },
        {
          name: "Grape",
          price: 23,
          image_url: "../assets/images/grape.jpg"
        }
      ]
    };
  },
  created() {
    var self = this;
    self.menuItems.map((x, i) => {
      self.$set(self.menuItems[i], "highlight", false);
    });
    var init = 0;
    setInterval(function() {
      if (init === self.menuItems.length) {
        init = 0;
      }
      self.menuItems[init].highlight = true;
      if (init === 0) {
        self.menuItems[self.menuItems.length - 1].highlight = false;
      } else {
        self.menuItems[init - 1].highlight = false;
      }
      init++;
    }, 2000);
  }
};
</script>

<style scoped>
.highlight {
  background-color: gray;
}
</style>

ItemImage.vue - almost empty ItemImage.vue -几乎是空的

<template>
  <div><p>Hello from ItemImage component</p></div>
</template>

<script>
export default {
  props: ["image_url"]
};
</script>

ItemsList iterates through each item and highlights it. ItemsList遍历每个项目并突出显示它。 I will need component ItemImage to show an image for that active/highlighted item.我需要组件ItemImage来显示该活动/突出显示的项目的图像。 URL for an image is item.image_url .图像的 URL 是item.image_url

Emit an event in ItemsList component with image_url and in Menu component pass image_url to ItemImage component as a prop.使用 image_url 在 ItemsList 组件中发出事件,在 Menu 组件中将 image_url 作为道具传递给 ItemImage 组件。 I did this in below codesandbox check it out.我在下面的代码中做了这个检查。

https://codesandbox.io/s/wild-moon-mbto4 https://codesandbox.io/s/wild-moon-mbto4

You can try with emitting an event from the child to the parent component.您可以尝试从子组件向父组件发出事件

In your child component ItemsList.vue , emit an event to the parent component (where the highlight property is set to true):在您的子组件ItemsList.vue 中,向父组件发出一个事件(其中 highlight 属性设置为 true):

created() {
    var self = this;
    self.menuItems.map((x, i) => {
      self.$set(self.menuItems[i], "highlight", false);
    });
    var init = 0;
    setInterval(function() {
      if (init === self.menuItems.length) {
        init = 0;
      }
      self.menuItems[init].highlight = true;

      //emit an event to trigger parent event
      this.$emit('itemIsHighlighted', menuItems[init].image_url)

      if (init === 0) {
        self.menuItems[self.menuItems.length - 1].highlight = false;
      } else {
        self.menuItems[init - 1].highlight = false;
      }
      init++;
    }, 2000);
  }

Then in your parent component Menu.vue :然后在您的父组件Menu.vue 中

<ItemsList @itemIsHighlighted="onItemHighlighted"/>
<ItemImage :image_url="this.selectedItem" ></ItemImage>

...

export default {
    data() {
        return {
            selectedItem: '' 
        } 
    }, 
    methods: {
        onItemHighlighted(value) {
            console.log(value) // someValue
            this.selectedItem = value
        }
    }
}

I couldn't test it, but I hope it helps.我无法测试它,但我希望它有所帮助。

You can also check this answer here.您也可以在此处查看答案。

PS Using Vuex would make this task a lot easier. PS 使用 Vuex 会让这个任务变得更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将值从一个组件传递到另一组件Angular 2(无父子关系) - How to pass a value from one component to another component Angular 2 (No parent child relationship) VueJs:如何使用 $emit(optionalPayload) 和 $on 将“计算函数”值从子组件传递到父组件? - VueJs: How to pass a 'computed function' value from child component to the parent component using $emit(optionalPayload) and $on? 如何将回调从一个子组件传递到另一个子组件 - How to pass callback from one child component to another 如何将数据从父 vuejs 传递给子组件 - How to pass data to child component from parent vuejs VueJS - 如何将 Axios 响应数据从父组件传递到子组件? - VueJS - How to pass Axios response data from parent to child component? 将数据从一个组件传递到另一个组件(不是子组件)? - Pass the data from one component to another component (not a child)? 如何将数组从一个子组件传递给另一个子组件? - How to pass an array from a child component to another child component? 如何在react js中将值从一个组件传递到另一个组件 - how to pass value from one component to another in react js 如何在 React 中将动态更新的值从一个组件传递到另一个组件? - How to pass dynamically updated value from one component to another in React? 如何将 state 变量的值从一个组件传递到另一个组件? - How to pass value of state variable from one component to another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM