本文同步發表於斜槓女紙部落格:Day18 閒不下來的史萊姆(一):將房間列表改用x-template 建立元件
鐵人賽進展到今天,默默地也快突破20天。前幾天寫完元件的基礎概念和範例以後,我的心一直有個小惡魔催促我打開VsCode專案把之前亂八糟的程式碼稍微整理一下。
然後我就打開VsCode惹!!!
首頁的房間列表頁面原始Code如下
<div class="col-xs-12 col-md-6 col-xl-4" v-for="item in rooms" :key="item.id">
<div class="room-list p-3 my-3" :class="'d-flex'">
<h3 class="room-title">{{item.name}}</h3>
<div class="card rounded-0">
<div class="card-body">
<figure class="room-thumb-img" :style="{ background: 'url('+ item.imageUrl +')' }">
<figcaption></figcaption>
</figure>
<div class=" d-flex room-info">
<div class="col-4">
<small>人數</small>
<p>1</p>
</div>
<div class="col-4">
<small>人數</small>
<p>1</p>
</div>
<div class="col-4">
<small>人數</small>
<p>18</p>
</div>
</div>
<div class="room-amenities">wifi , 早餐 , 電話 , 空調 , 冰箱 , 禁止吸煙 , 可帶寵物</div>
<div class="room-price">
<div><span>假日</span><span class="h-price pr-0">${{item.holidayPrice}}</span></div>
<div><span>平日</span><span class="n-price pr-0">${{item.normalDayPrice}}</span></div>
</div>
</div>
</div>
</div>
</div>
這邊根據Day15 萬丈高樓平地起(3):元件 Components 簡介所介紹的x-template
元件方法改寫後如下:
//HTML
<card-rooms :room-lists="item" v-for="item in rooms" :key="item.id" v-if="item.imageUrl"></card-rooms>
//x-template
<script type="text/x-template" id="cardElement">
<div class="col-xs-12 col-md-6 col-xl-4">
<div class="room-list p-3 my-3" :class="'d-flex'">
<h3 class="room-title">{{roomLists.name}}</h3>
<div class="card rounded-0">
<div class="card-body">
<figure class="room-thumb-img" :style="{ background: 'url('+ roomLists.imageUrl +')' }">
<figcaption></figcaption>
</figure>
<div class=" d-flex room-info">
<div class="col-4">
<small>人數</small>
<p>1</p>
</div>
<div class="col-4">
<small>人數</small>
<p>1</p>
</div>
<div class="col-4">
<small>人數</small>
<p>18</p>
</div>
</div>
<div class="room-amenities">wifi , 早餐 , 電話 , 空調 , 冰箱 , 禁止吸煙 , 可帶寵物</div>
<div class="room-price">
<div><span>假日</span><span class="h-price pr-0">${{roomLists.holidayPrice}}</span></div>
<div><span>平日</span><span class="n-price pr-0">${{roomLists.normalDayPrice}}</span></div>
</div>
</div>
</div>
</div>
</div>
</script>
//JS
Vue.component('card-rooms', {
props: ['roomLists'],
template: '#cardElement',
});
<card-rooms>
標籤包裹,利用v-if
排除因為ajax延遲
而導致的報錯問題。#cardElement
包裹在x-template
元件中Vue.component
和props
完成元件和畫面的資料串連今天就先到這囉,明天我們繼續看下去~