Vue 全局注冊組件和局部注冊組件


 Vue 組件化的思想大大提高了模塊的復用性和開發的效率,在使用組件時,一般分為幾個步驟,分別是:定義組件、引入組件,注冊組件,使用組件。本節主要針對Vue中如何注冊組件進行闡述。

 下面我們一起來看如何全局注冊組件,如何局部注冊組件。

 

 頁面顯示結果如下:

【說明】:

1. com-one  com-two 為全局注冊組件, com-three  com-four 為局部注冊組件;

2. 全局注冊組件為 Vue.component()方法;局部注冊組件為 components 屬性,它的屬性值是一個對象;

3. 在用腳手架時,我們更多用到的是在單文件組件中局部注冊組件。

 

[代碼]:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test1</title>
</head>
<body>
    <div id="app">
        <com-one></com-one>  <com-two></com-two>
       
        <com-three></com-three>  <com-four></com-four> 
    </div>
</body>
<!-- 定義組件 -->
<template id="comTwo">
    <div>
       <h1>this is com-two</h1>
    </div>
</template>
<template id="comFour">
    <div>
        <h2>this is com-four</h2>
    </div>
</template>
<script src="./vue.js"></script>
<script>
// 全局注冊1: 第二個參數中template的屬性值為子組件的具體內容(注冊時定義組件)
Vue.component('com-one',{
    template: `<h1>this is com-one</h1>`
})

// 全局注冊2: 第二個參數中template的屬性值為<template>模板的'#id'
// (將子組件的具體內容單獨寫入<template>中,放到<body>元素之后,<script>元素之前)
Vue.component('com-two',{
    template: '#comTwo',
})

let vm = new Vue({
    el: '#app',
    data: {},
    // 局部注冊:(類似於全局注冊)
    components: {
        "com-three": {
            template: `<h2>this is com-three</h2>`
        },
        "com-four": {
            template: '#comFour'
        }
    }
})
</script>
</html>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM