[前端史萊姆與Vue的三十天時光冒險]Day18 閒不下來的史萊姆(一):將房間列表改用x-template 建立元件

Mio
斜槓女紙
Published in
Oct 4, 2019

有時我也懷疑自己是否勞碌命…

鐵人賽進展到今天,默默地也快突破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延遲而導致的報錯問題。
  • 將原本的HTML程式碼以#cardElement包裹在x-template元件中
  • 最後使用Vue.componentprops完成元件和畫面的資料串連

今天就先到這囉,明天我們繼續看下去~

你有更多的問題嗎?你有什麼建議呢?
歡迎在下方留言,或加入我的臉書粉絲頁一起討論!

【免費支持】如果你幫我拍手5下,我有機會得到內容創作的酬勞🙂

--

--

Mio
斜槓女紙

每天努力克服拖延症,致力於斜槓人生。