iT邦幫忙

0

【Vue】幫卡片式排版加上假資料 |components v-for & data

7514 2021-11-30 23:25:351039 瀏覽

作法

定義好單一元件 (template+區域樣式),在畫面內引入元件,並根據需求再做調整如:樣板迴圈 v-for、傳資料回元件。不將資料寫在小元件內,是避免後續又有其他頁面需要用到此元件時,裡面會有不必要的資料。
https://ithelp.ithome.com.tw/upload/images/20211130/20144231YZy7Kjtc8R.png

定義單一元件(template/script/style)

script 設定 props 等待資料從外層傳回來。
Stickers.vue*

<template>
    <div>
        <div class="img-center">
            ...
        </div>
        <div class="text">
            <h3>{{ spotName }}</h3>
            <img src="../assets/location.svg"><span>{{ spotLocation }}</span>
        </div>
    </div>
</template>

<script>
export default {
    name: "Stickers",
    props: ['spotName', 'spotLocation']
}
</script>

<style scoped lang="scss">
    ...
</style>

利用迴圈複製元件並加上資料

Home.vue*

<template>
   <div>
        <stickers v-for="(spot, index) in hotSpots" 
        :spot-name="hotSpots[index].name" 
        :spot-location="hotSpots[index].location">
        </stickers>
   </div>
</template>

<script>
import Stickers from "@/components/Stickers.vue";

export default {
  name: 'Home',
  data: ()=> ({
    hotSpots: [
      { name:'花園夜市', location: '台南市' },
      { name:'孔廟', location: '台南市' },
      { name:'101大樓', location: '台北市' },
      { name:'象山', location: '台北市' }
    ]
  }),

  components: {
    Stickers
  }
}
</script>

資料來源:
https://www.youtube.com/watch?v=W2j7CjQI2y4&t=340s
https://book.vue.tw/CH2/2-2-communications.html
https://medium.com/pierceshih/vue-js-學習筆記-day6-v-for-列表渲染-基礎篇-79fb79d5fcb


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言