首页 > 解决方案 > 如何让一个组件与另一个组件对应特定功能

问题描述

我有一个组件,可以在其中单击机器的颜色,当我更改颜色时,机器会在图像轮播中加载不同的颜色。

现在我还在底部创建了一个组件,其中包含同一台机器的图片库。当我单击页面顶部的颜色按钮时,如何使图片库也改变颜色?

重要提示:这两个组件不在同一个父组件中,但它们已经加载到同一个机器映像中,所以我相信这些方法没有错。

这是可点击的颜色按钮:

 <li
            v-for="(color, index) in machine.content[0].machine_colors"
            :key="color.color_slug"
            v-if="color.inStock"
            v-on:click="selectColor(index)"
            v-bind:class="{ active: (color.color_slug === selectedColor.color_slug)}">
            <img v-bind:src="color.color_dash">
          </li>

这是改变颜色的组件:

<div class="product__carousel">
      <Carousel showIcon v-if="selectedColor" :machineColor="selectedColor"/> <!-- Image carousel gets loaded in -->
    </div>

以及需要更改颜色但不需要更改颜色的组件:

<div id="tab-two-panel" class="panel">
           <footerGallery  v-if="selectedColor && machine" :machineColor="selectedColor"/>
      </div>

下面是部分组件的脚本:

export default {
name: 'aboutMachine',
components: {
  Collapse,
  footerGallery,
},
data() {
  return{
    selectedColor: this.getMachineColorContent(),
  }
},
props: {
  main: {
    default () {
      return {};
    },
  },
  machine: {
    default () {
      return {};
    },
  },
},
 methods: {
getMachineColorContent() {
  if (this.selectedColor) {
    return null;
  }
  return this.machine.content[0].machine_colors[0];
},
selectColor(index) {
  this.selectedColor = this.machine.content[0].machine_colors[index];
},

}, } 和组件本身:

export default {
name: 'footerGallery',
props: {
  showIcon: Boolean,
  machineColor: {
    default () {
      return {};
    },
  },
},
data() {
  return {
    highLightedThumbIndex: 0,
    isActive: undefined,
  };
},
created() {
  this.highLightedThumbIndex = this.highLightedThumbIndex || 0;
},
methods: {
  selectThumb(index) {
    this.highLightedThumbIndex = index;
  },
},

};

这是我的 main.js

import Vue from 'vue';
import VueYouTubeEmbed from 'vue-youtube-embed'

import FontAwesome from './libs/fa';
import App from './App';

const eventHub = new Vue();
Vue.use(VueYouTubeEmbed);
Vue.component('font-awesome-icon', FontAwesome);

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
});

标签: htmljsonvue.jsvue-component

解决方案


我会使用事件来实现这一点。Vue2的迁移指南对如何在不使用完整的 Vuex 解决方案的情况下进行简单的事件路由进行了很好的简短说明。在您的情况下,您将在您的一个 js 文件中声明一个全局事件中心:

var eventHub = new Vue();

在您的 selectColor 方法中,您将发出选定的索引:

selectColor(index) {
    this.selectedColor = this.machine.content[0].machine_colors[index];
    eventHub.$emit("select-color",index);
}

在页脚中,您将为调用 selectThumb 的 select-color 事件注册一个侦听器,该事件的有效负载(即选定的索引):

created() {
    this.highLightedThumbIndex = this.highLightedThumbIndex || 0;
    eventHub.$on("select-color",this.selectThumb);
}

推荐阅读