完整源代码:https ://github.com/tenzan/menu-ui-tw
演示:https ://flamboyant-euclid-6fcb57.netlify.com/
目标:
ItemsList
并且ItemImage
是 的子组件Menu.vue
。我需要传递image_url
fromItemsList
到ItemImage
,以更改右侧的图像,在左侧的项目按时间间隔自动更改后。
- 左侧:组件
ItemsList.vue
- 右侧:组件
ItemImage.vue
组件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>
项目列表.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 -几乎是空的
<template>
<div><p>Hello from ItemImage component</p></div>
</template>
<script>
export default {
props: ["image_url"]
};
</script>
ItemsList遍历每个项目并突出显示它。我将需要组件ItemImage来显示该活动/突出显示的项目的图像。图片的 URL 是item.image_url
.