iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
0
Modern Web

Vue菜鳥的自我學習days系列 第 15

15.建立商品詳情內容

  • 分享至 

  • xImage
  •  

利用 props 將外部資料導至 component 內,在商品列表每個項目的 onClick 事件將該商品資料動態的更改 props
值,如此達到動態更改商品資訊區塊內容。
在 components 底下新增 ProductInfo.vue 檔案:
注意之後的 style 標籤上都加上了 scoped attribute,目的是宣告該 style 的內容只針對該 component 的
樣式設定

<template>
<div>
<h2>Product Info</h2>
<div class="product-container">
<div class="product-title">{{ product.name }}</div>
<div class="product-image">
<img :src="product.imgUrl" />
</div>
<div class="product-info">
<div class="product-content">{{ product.desc }}</div>
<span class="product-price">{{ product.price | currency }}</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ProductInfo',
props: {
item: {
Object,
default: {},
},
},
data() {
return {
product: this.item,
};
},
watch: {
item(value) {
this.product = value;
},
},
};
</script>
<style scoped>
.product-container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
background: #eee;
border-radius: 3px;
font-family: sans-serif;
}
.product-title {
width: 100%;
padding: 10px 20px;
font-size: 2.5em;
}
.product-image {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
padding: 10px;
}
.product-image img {
align-self: center;
width: 60%;
height: auto;
border: 1px solid #ddd;
border-radius: 5px;
}
.product-info {
width: 100%;
padding: 10px;
}
.product-content {
width: 100%;
font-size: 1.5em;
}
.product-price {
color: rgba(255, 30, 0, 0.884);
font-size: 2em;
float: right;
}
</style>

透過使用 props 接收外部資料,並讓 data.product 初始值指定為該商品資料:

{
...
props: {
item: {
type: Object,
default() {
return {};
},
},
},
data() {
return {
product: this.item,
};
},
...
}

另外,因為商品詳細資料會隨著選擇的商品不同而有不同內容,因此在 watch 加入 item 監控,以更新
data.product

{
...
watch: {
item(value) {
this.product = value;
},
},
}

上一篇
14.filters
下一篇
16.建立商品詳情內容2
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言