iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
1
自我挑戰組

Vue 與 Element UI 兩三事系列 第 7

Vue 與 Element UI 兩三事#7 組件 component(1)

  • 分享至 

  • twitterImage
  •  

前言:
如今,前端程式設計中,我們越來越希望將類似的內容整合在一起,開放幾個能夠客製化的接口就好,一方面能夠減少維護時看到一長串代碼時的無力感,一方面也是能夠提高開發速度並且使代碼結構乾淨,今天我們就來介紹減少重複造輪子的功能,組件吧
正文:
我們先來看一下一個 vue 組件長怎樣吧


<div id="app">
    <test-counter></test-counter>
    <test-counter></test-counter>
    <test-counter></test-counter>
</div>

Vue.component('test-counter',{
    data: funciton(){
        return {
            count: 0
        }
    },
    template: '<button @click="count++">click me {{count}}</button>'
})
let app = new Vue({
    el: '#app'
})
  • 我們在上方建立了一個名為 button-counter 的組件,當我們需要使用他的時候只需要創造一個元素名稱為 button-counter 的元素即可
  • 觀看上方組件,可以發現其 data 的使用方始與以往不同,原因是因為我們希望每個組件可以各自維護其自己的 data,因此每個實例皆為獨立的返回函式
  • 我們在 template 這邊撰寫要產生的 html 模板,當調用組件時就會將其渲染出來
    https://ithelp.ithome.com.tw/upload/images/20200907/20109403EyPUPGFWTp.png
    在建立了基本的組件後,我們希望可以在 vue 實例中傳遞數值給組件,這邊要介紹的是 props 屬性
    組件的概念非常單純,大致上來說就是宣告一個屬性,外部會給予此屬性所需要獲得的內容,並且在內部將此屬性綁定到需要此數據的元素上,下面提供一個簡短的範例
<breakfast-meau v-for="(item,index) in meau" :key="index" :meau="item"></breakfast-meau>

Vue.component('breakfast-meau', {
    props: ['meau'],
    template: '<div class="breakdast-item">{{meau}}</div>'
})

let app = new Vue({
    el: '#app',
    data: {
        meau: ['egg','bread','salad']
    }
})

https://ithelp.ithome.com.tw/upload/images/20200907/201094033QErLMfafx.png

嘮叨一下:
第一個星期一,也算開始進入狀態了,寫鐵人的時間擠擠總是會有的~


上一篇
Vue 與 Element UI 兩三事#6 第一周回顧
下一篇
Vue 與 Element UI 兩三事#8 組件component(2)
系列文
Vue 與 Element UI 兩三事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言