html - 如何让一个组件与另一个组件对应特定功能
问题描述
我有一个组件,可以在其中单击机器的颜色,当我更改颜色时,机器会在图像轮播中加载不同的颜色。
现在我还在底部创建了一个组件,其中包含同一台机器的图片库。当我单击页面顶部的颜色按钮时,如何使图片库也改变颜色?
重要提示:这两个组件不在同一个父组件中,但它们已经加载到同一个机器映像中,所以我相信这些方法没有错。
这是可点击的颜色按钮:
<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/>',
});
解决方案
我会使用事件来实现这一点。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);
}
推荐阅读
- python - `concurrent.futures` 中的 `with` 函数
- android-studio - 重新加载片段后视图模型不返回任何数据
- python - ARM Thumb BL 指令循环到自身
- python - 当它是类的属性时,格式化硒定位器的正确方法是什么?
- css - 我应该对我的汉堡包进行什么轮换?
- javascript - 我可以通过鼠标点击在 Jekyll 主题之间切换吗?
- c# - 有什么方法可以将表单应用于所有列或整个表?
- ios - Firebase Crashlytics 无法与 DJI iOS SDK 一起使用
- delphi - 如何使用泛型创建不同类型的 MDI 子项?
- javascript - Google Apps 脚本中的去抖动或限制事件处理程序