1. 程式人生 > >vue元件的四種寫法

vue元件的四種寫法

資料驅動和元件化是vue.js兩個最重要的特點。元件化是為了方便程式碼複用,提高開發效率。常見的vue元件寫法有四種,各有特色,適用於不同的場景。

1.全域性元件

結構:
// 元件的註冊
Vue.component( 'componentName', {
    template:  // 元件的html結構,
    data(){
        return{
            // 元件中的屬性
        }
    },
    method: {
        // 元件中的方法
    }
    ...... // 元件其他的屬性和方法
})
 
// 元件的使用
new Vue({ el: '#app' })

在script標籤內通過Vue.component()定義一個全域性元件,並通過new Vue()例項將元件應用到html檔案中id為app的標籤內。

特點:

<1>可以直接在html檔案中的script標籤內直接定義與使用;

<2>通過該方法定義的元件是全域性元件,在任何Vue例項下都可以使用,適合專案比較簡單的場景;

<3>每次定義元件時都要重新使用Vue.component(),且元件名不能相同;

2.區域性元件

結構:
// 構造元件物件
const componentName =
{ template: // 元件的html結構, data(){ return{ // 元件中的屬性 } }, method: { // 元件中的方法 } ...... // 元件其他的屬性和方法 } // 元件的使用 new Vue({ el: '#app', components: { // 元件註冊、呼叫 componentName } })

在script標籤中通過定義一個元件物件,並通過Vue例項中components屬性將該元件註冊呼叫。

特點:

<1>與全域性方式定義的元件相似,都可以直接在html檔案中的script標籤中直接書寫元件與使用;

<2>只有在註冊過的Vue例項中才能使用該元件;

3、使用template標籤

結構:
<template id="componnet">
    // 元件的html結構
</template>
// 全域性元件的註冊與使用
Vue.component( 'componentName', {
    template:  '#component',
    data(){
        return{
            // 元件中的屬性
        }
    },
    method: {
        // 元件中的方法
    }
    ...... // 元件其他的屬性和方法
})
 
new Vue({
    el: '#app'
})
// 區域性元件的註冊與使用
const componentName = {
    template:  '#component',
    data(){
        return{
            // 元件中的屬性
        }
    },
    method: {
        // 元件中的方法
    }
    ...... // 元件其他的屬性和方法
}
 
new Vue({
    el: '#app',
    components: {
        // 元件註冊、呼叫
        componentName
    }
})

使用template標籤將元件中的html結構寫在body標籤內部,在script標籤內按照全域性元件和區域性元件的方式註冊與使用。不同之處在於元件中template屬性是通過id引用。

特點:

<1>js檔案中不包含html結構內容,實現結構與邏輯分離;

4、單檔案元件

結構:
<template lang="html">
    // 元件中的html結構
</template>

<script>
    //元件的邏輯
    export default {
        // 元件的屬性和方法
    }
</script>

<style lang="css" scoped>
    // 元件的樣式
</style>

建立一個尾綴為vue的檔案,檔名即為元件名。元件內包含三部分內容:html結構、js邏輯、css樣式,分別對應於不同的標籤。使用時元件時,通過import引入即可使用。

特點:

<1>元件與元件之間互不影響,複用性高,其html、css、js均可複用;

<2>元件的結構、邏輯清晰;

<3>適用於大型複雜專案,適合多人開發;