Vue框架入門(一)

一、概述

1.1 關於Vue的說法

  • vue 是一套構建用戶界面的流行的漸進式前端框架。
  • vue 只關注視圖層, 採用自底向上增量開發的設計。
  • vue 的目標是通過儘可能簡單的 API 實現響應的數據綁定和組合的視圖組件。
  • vue是基於MVVM模式的具體實現。
  • vue 的核心庫只關注視圖層。
  • 便於與第三方庫或既有項目整合。
  • vue的其他擴展庫可以高效的進行前後臺分離的開發模式,常用的開發庫又稱爲vue全家桶。

Vue在線教程:https://cn.vuejs.org/v2/guide/index.html

1.2 下載和安裝

  • 運行環境:nodejs

下載地址:https://nodejs.org/en/download/

  • 開發工具:visual code studio

下載地址:https://visual-studio-code.en.softonic.com/

  • vue核心庫

下載地址:https://cn.vuejs.org/v2/guide/installation.html

1.3 Hello World

第一步:新建一個html頁面,引入vue核心庫。

<script src="js/vue.js" type="text/javascript"></script>

第二步:編寫vue代碼。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
        <title></title>
        <!-- <script src="https://cdn.jsdelivr.net/npm/vue" type="text/javascript"></script> -->
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>1-基本綁定</h4>
        <div id="app">
            {{ message }}
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                    message: 'Hello Vue'
                }
            })
        </script>
	</body>
</html>

第三步:在瀏覽器上打開該html頁面即可看到下面效果。
在這裏插入圖片描述

二、Vue對象詳解

2.1 創建Vue對象

每個 Vue 應用都是通過用 Vue 函數創建一個新的 Vue 實例開始的。一個vue應用至少包含一個vue實例對象。

基本語法:

new Vue({
	// 選項
}) 

2.2 選項詳解

Vue實例可以包含以下選項:

  • 數據屬性與方法:當前實例閉包內的全局變量以及全局方法。
  • 操作dom:用於生成dom或綁定dom。
  • 生命週期鉤子函數:用於在vue組件或vue實例在創建以及渲染的過程中植入用戶的可執行程序。
  • 資源:引入組件或實例所引用的指令、組件、過濾器等。
  • 其他:name屬性、minxin混合等。

常用的數據屬性與方法:

  • data:Vue 實例的數據對象, Vue 將會遞歸將 data 的屬性轉換爲 getter/setter方法,從而對data進行賦值。
  • props:props 可以是數組或對象,用於接收來自父組件的數據,訪問時與data基本一致,只有組件具備,vue實例對象不具備。
  • computed:計算屬性,內容爲返回計算結果的函數。
  • methods:實例或組件的內置函數。
  • watch:觀察對象,當數據變化時可觸發watch中的內置函數。

操作dom:

  • el:只在vue實例中生效,用於綁定實例對象對應的dom對象的id屬性。
  • template:vue實例對象或組件的模板語法,模板中除標準的html語法還包括vue的自定義指令以及表達式等。
  • render:以創建dom對象的方式聲明dom結構,在vue中不常用。

聲明週期鉤子函數:在vue對象以及組件從創建、渲染、數據改變等週期內,提供給用戶的對外函數接口。

  • created:function() {} 在vue對象創建時被調用。

資源類屬性:

  • directives:本組件包含的用戶自定義指令集合。
  • filters:本組件包含的過濾器。
  • components:本組件或本實例包含的組件。

其他屬性:

  • Name:標註當前組件名稱
  • minxin:用於將當前數據屬性混入到組件配置屬性中。
  • parent:指定當前組件的父實例(組件)。

2.3 data屬性

2.3.1 data屬性用法

實例中的data對應的是一個對象。例如:

new Vue({
	data: {
		message: 'hello vue'
	}
})

組件中的data對應的是一個函數,需要在函數中聲明當前組件的數據屬性。

Vue.component({
	data: function() {
		return {
			message: 'hello vue component'
		}
	}
})

2.3.2 data屬性的使用方式

可以使用this關鍵字訪問vue實例屬性,也可以使用實例變量訪問。例如:

let app = new Vue({
	el: '#app',
	data: {
		message: 'hello vue'
	},
	methods: function() {
		setMessage: function() {
			this.message = 'hello java'
			console.log(app.message)
			
			// 在methods中擴展vue實例屬性,vue無法識別
			// this.newMessage = 'hello react'  
		}
	}
})

2.3.3 vue實例對外暴露的屬性和方法

$el :獲取vue實例對應的dom對象;
$data :獲取vue實例的data對象;

例如:

new Vue({
	el: '#app',
	data: {
		message: 'hello vue'
	},
	methods: {
		getAttribute: function() {
			console.log(this.$el === document.getElementById('app')) // true
			this.$data.message = "新數據";
		}
	}
})

三、基本功能介紹

3.1 基本數據綁定

vue實現了mvvm模式,用戶只需要配置view、model,vue則直接實現了viewmodel,並直接展現視圖。

基本語法:

{{js表達式}}

在這裏插入圖片描述
js表達式的特點:

  • 內容爲單句js語句。
  • 表達式不支持賦值(如 var I = 1);
  • 表達式支持三目運算符。
  • 在表達式中可以訪問組件的屬性與方法,省略this調用。
  • 表達式支持使用原生js對象(如Date等)。

3.2 元素屬性綁定

通過vue可以將model層的數據與元素的基本屬性綁定,從而對元素屬性賦值。

基本語法:

<標籤名 v-bind:屬性名="js表達式">
	標籤內容...
</標籤名>

例如:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>2-元素屬性綁定</h4>
        <div id="app">
            <span v-bind:title="message">
                鼠標懸停幾秒鐘查看此處動態綁定的提示信息!
            </span>
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                    message: '頁面加載於' + new Date().toLocaleString()
                }
            })
        </script>
	</body>
</html>

v-bind指令縮寫爲:

<span :title="message">
    鼠標懸停幾秒鐘查看此處動態綁定的提示信息!
</span>

3.3 條件判斷

vue中提供了類似於if、else的語法來實現邏輯判斷。

基本語法:

<標籤名 v-if="實例對象屬性">
	標籤內容...
</標籤名>

如果v-if取值爲true,則加載v-if標籤內容;如果如v-if取值爲false,則無需加載。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>3-條件判斷</h4>
        <div id="app">
            <p v-if="seen">現在您看到我了</p>
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                   seen: true
                }
            })
        </script>
	</body>
</html>

3.4 循環

v-for模板指令來循環vue實例中的屬性。

基本語法:

<標籤名 v-for="變量名 in 實例對象屬性">
	標籤內容...
</標籤名>

實例對象屬性應該是數組或集合類型。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>4-循環</h4>
        <div id="app">
           <ul>
               <li v-for="todo in todoList">
                    {{todo.text}}
               </li>
           </ul>
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                   todoList: [
                       {text: 'java'},
                       {text: 'php'},
                       {text: 'android'},
                       {text: 'ios'},
                   ]
                }
            })
        </script>
	</body>
</html>

3.5 數據雙向綁定

單向綁定:view中的顯示數據與vue實例中的屬性綁定即使單項綁定,此時vue實例中的屬性變化會同步到view的顯示數據中。
雙向綁定:用於表單標籤(例如:文本框),表單標籤的內容與綁定的vue實例中的屬性雙向同步。雙向綁定意味着任意一方改變都會影響另一方的取值。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>5-數據雙向綁定</h4>
        <div id="app">
            <input v-model="message" />
            <button v-on:click="setValue">設置值</button>
            <button v-on:click="getValue">獲取值</button>
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                    message: ''
                },
                methods: {
                    setValue() {
                        this.message = '呵呵'
                    }, 
                    getValue() {
                        alert(this.message);
                    }
                }
            })
        </script>
	</body>
</html>

3.6 計算屬性

計算屬性函數用於返回計算結果。在此函數內可以訪問vue組件的屬性與方法。
計算函數一般在組件或實例對象的computed中聲明,然後在模板中直接訪問該函數即可。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>7-計算屬性</h4>
        <div id="app">
            出生日期:<input type="date" v-model="birthday"/><br/>
            <!-- v-model屬性綁定了age函數,該input的內容會根據age函數返回值發生變化 -->
            年齡:<input type="number" v-model="age"/><br/>
        </div>
        <script>            
            let vue = new Vue({
                el: '#app',
                data: {
                    birthday: '2012-12-12'
                },
                computed: {
                    // 只要data中任意屬性發生變化,都會觸發該函數
                    // 該函數的返回值作爲v-model="age"文本框的內容
                    age: function() { 
                        return new Date().getFullYear() - new Date(this.birthday).getFullYear()
                    }
                }
            })
        </script>
	</body>
</html>

計算屬性與函數的區別?

  • 相同點:

在模板中使用的方式相同,傳遞參數的方式相同。

  • 不同點:

1)函數在methods中聲明,計算屬性在computed中聲明;
2)計算屬性需要返回結果,而函數非必須返回結果;
3)計算屬性是基於依賴進行緩存的,意味着只有影響計算結果的屬性發生改變的時候纔會重新計算,而函數每次調用都會運算;

3.7 觀察屬性

觀察屬性:當data發生變化時,vue會調用觀察屬性綁定的函數,因此也叫監聽器。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>8-觀察屬性</h4>
        <div id="app">
            出生日期:<input type="date" v-model="birthday"/><br/>
        </div>
        <script>            
            let vue = new Vue({
                el: '#app',
                data: {
                    birthday: '2012-12-12'
                },
                watch: {
                	// 監聽屬性名字與data屬性名字相同
                    // 當data發生變化時,該函數會自動觸發
                    birthday: function() {
                        alert(vue.birthday)
                    }
                }
            })
        </script>
	</body>
</html>

監聽器函數封裝在watch屬性中,函數名與監聽的數據屬性名必須相同。只有在數據屬性變化時,監聽器函數將會被調用。

3.8 設置樣式

3.8.1 通過數據屬性設置樣式

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <style>
            .ba {
                color: red;
            }

            .cr {
                background: aqua;
            }
        </style>
	</head>
	<body>
        <h4>9-設置樣式</h4>
        <div id="app">
            <!-- 如果error或warn屬性爲true,那麼就設置class屬性爲ba或cr -->
            <!-- <div v-bind:class="{ba:error, cr:warn}">樣式</div> -->
            
            <div v-bind:class="bb">樣式</div>
        </div>
        <script>            
            let vue = new Vue({
                el: '#app',
                data: {
                    error: true,
                    warn: true,
                    // 如果ba爲true,則返回ba;如果ba爲false則不返回
                    // 如果cr爲true,則返回cr;如果cr爲false則不返回
                    bb: {ba:false, cr:true}
                }
            })
        </script>
	</body>
</html>

3.8.2 通過函數設置樣式

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <style>
            .ba {
                color: red;
            }

            .cr {
                background: aqua;
            }
        </style>
	</head>
	<body>
        <h4>10-通過函數計算樣式</h4>
        <div id="app">
            <span v-bind:class="getClass">樣式1</span>
            <span v-bind:style="getStyle">樣式2</span>
        </div>
        <script>        
            let st = {
                name: 'jacky',
                sex: 0
            }
            
            let vue = new Vue({
                el: '#app',
                computed: {
                    getClass: function() {
                        // 返回class名字(ba或cr)
                        return {ba:st.sex == 1, cr:st.sex == 0}
                    },
                    getStyle: function() {
                        // 返回樣式單
                        return "color:blue;font-size:30px;"
                    }
                }
            })
        </script>
	</body>
</html>

3.9 事件處理

v-on指令:監聽 DOM 事件,並在觸發時運行用戶編寫的js代碼。v-on可以綁定幾乎全部的事件類型。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>11-事件處理</h4>
        <div id="app">
            <button v-on:click="minus">-</button>
            {{count}}
            <button v-on:click="add">+</button>
        </div>
        <script>
            let vue = new Vue({
                el: '#app',
                data: {
                    count: 0
                },
                methods: {
                    add: function() {
                        this.count++
                    },
                    minus: function() {
                        if (this.count > 0) {
                            this.count--
                        }
                    }
                }
            })
        </script>
	</body>
</html>

v-on指令縮寫爲@

<button @click="minus">-</button>
{{count}}
<button @click="add">+</button>

3.10 函數傳參

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        
	</head>
	<body>
        <h4>11-參數傳遞</h4>
        <div id="app">
            <button v-on:click="add(2, $event)">+2</button>
            {{count}}
        </div>
        <script>        
                    
            let vue = new Vue({
                el: '#app',
                data: {
                    count: 0
                },
                methods: {
                    // e是dom的event對象
                    add: function(num, e) {
                        this.count = num + this.count;
                    }
                }
            })
        </script>
	</body>
</html>

上面v-on指令的取值處直接調用add函數並傳遞參數,在模板中可以使用$event獲取到event對象,並傳遞給響應函數。

3.11 表單

vue通過v-model指令將dom元素與數據屬性雙向綁定,其工作原理:
1)監聽用戶的輸入事件以更新數據;
2)監聽數據更新dom元素取值;

vue通過以下監聽事件來監控dom元素的屬性變化。

dom元素 監聽屬性 監聽事件
text\textarea value input
checkbox\radio checked change
select value change

示例代碼:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        
	</head>
	<body>
        <h4>13-表單</h4>
        <div id="app">
            <form>
                <!-- 如果沒有lazy,那麼修改輸入框內容,span標籤內容也會發生變化 -->
                <!-- 如果指定了lazy,那麼修改輸入框內容,span標籤內容不會馬上發生變化,只有輸入框失去焦點後,span標籤內容纔會發生變化 -->
                <input v-model.lazy="msg" v-on:change="getLength"/>
                <span>{{msg}}</span>
                <br/>
                <input v-model.number="age" type="number" />
                <br/>
            </form>
        </div>
        <script>        
                    
            let vue = new Vue({
                el: '#app',
                data: {
                    msg: 'hello',
                    age: 0
                },
                methods: {
                    getLength: function() {
                        console.log("msg length is " + this.msg.length)
                    }
                }
            })
        </script>
	</body>
</html>

我們可以在vmodel後面指定修飾符:
vmodel.lazy:一般適用於text,將數據屬性更新的事件由input轉變爲使用 change 事件進行同步。
vmodel.number:將用戶的輸入值轉爲數值類型。
vmodel.trim:自動過濾用戶輸入的首尾空白字符。

例如:

<input vmodel.lazy="message" />
<input vmodel.number="age" />
<input vmodel.trim="msg" />

它們也可以組合在一起使用:

<input vmodel.lazy.trim="message" />

3.12 組件

組件是可複用的 Vue 實例,一個組件映射着一個MVVM模型,聲明一個組件後,在其他實例或組件中使用組件標籤直接調用即可完成組件的顯示。一個大型的工程由多個可視化可視化界面,每個界面都是由多個組件組成。
在這裏插入圖片描述

3.12.1 組件註冊

組件的註冊:聲明組件模板內置函數。

基本語法:

Vue.component('組件名', { 
	data: function() {
		return {
			// 組件全局變量
		}
	},
	template: 'html模板',
	methods: {
		// 方法屬性
	},
	computed: {
		// 計算屬性
	}
})

與實例對象不同,組件中的data是一個函數,函數的返回值爲全局變量。
與實例對象不同,組件中很少使用el,都是用template聲明模板,在模板中要包含根節點。

// 註冊組件        
Vue.component('button-counter', {
    // 定義組件中的全局變量
    // 該變量在組件中可以訪問
    data: function() {
        return {
            count: 0
        }
    },
    // 定義組件模板
    template: '<button v-on:click="count++">{{count}}</button>'
}) 

組件引用:

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

注意:如果組件名是多個英文組成的字符串,那麼引入組件時候多個英文之間使用橫槓分割。

示例代碼:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <script>
                      
        </script>
	</head>
	<body>
        <h4>14-組件</h4>
        <div id="app">
            <!-- 使用組件 -->
            <button-counter></button-counter>
            <button-counter></button-counter>
            <button-counter></button-counter>
        </div>
        <script>
            // 註冊組件        
            Vue.component('button-counter', {
                // 定義組件中的全局變量
                // 該變量在組件中可以訪問
                data: function() {
                    return {
                        count: 0
                    }
                },
                // 定義組件模板
                template: '<button v-on:click="count++">{{count}}</button>'
            }) 
            
            // 在實例中應用組件
            let vue = new Vue({ 
                el: '#app',
                data: {

                }
            })
        </script>
	</body>
</html>

3.12.2 props屬性

props屬性主要用於父組件向子組件中傳遞參數。props中聲明的屬性是全局屬性,可以在方法、計算屬性中訪問。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <script>
                      
        </script>
	</head>
	<body>
        <h4>15-props屬性</h4>
        <div id="app">
            <!-- 普通屬性傳遞 -->
            <blog-component blog-title="測試"></blog-component>
            <!-- 組件屬性傳遞 -->
            <blog-component v-bind:blog-title="posts[0].title"></blog-component>
        </div>
        <script>
            // 定義一個組件        
            Vue.component('blog-component', {
                props: ['blogTitle'],
                template: '<h3>{{blogTitle}}</h3>'
            }) 
            
            // 在實例中應用組件
            let vue = new Vue({ 
                el: '#app',
                data: {
                    posts: [
                        { id: 1, title: 'My journey with Vue' },
                        { id: 2, title: 'Blogging with Vue' },
                        { id: 3, title: 'Why Vue is so fun' }
                    ]
                }
            })
        </script>
	</body>
</html>

Post的命名規則 :在定義prop時可以使用camelCase和kebab-case兩種方式。但在模板中引入組件時,由於html是忽略大小寫的,因此只能使用kebab-case方式引入。

在聲明屬性時可以設定屬性的數據類型,如果傳入的屬性與類型不符合,將會提示相關的錯誤信息。

Vue.component('blog-component', {
   props: {
        blogTitle: String
    }, 
    template: '<h3>{{blogTitle}}</h3>'
}) 

上面程序指定blogTitle的類型爲String,那麼傳入屬性必須是字符串類型,否則報錯。

下面是常見的數據類型:
在這裏插入圖片描述

3.12.3 子組件捕獲事件

當觸發子組件的事件處理函數後,需要調用父組件的響應函數進行響應。

在父組件中通過v-on:method方式註冊自定義處理函數,例如:

<blog-post v-on:enlarge-text="處理函數"></blog-post>

在子組件中使用emitemit方法通知父組件“處理函數”執行。emit方法的參數名對應着v-on事件名。

Vue.component('blog-post', {
     props: ['post'],
     template:  // $emit方法傳入事件名稱來觸發一個事件
         `<div class="blog-post">
             <h3>{{post.title}}</h3>
             <button @click="$emit('enlarge-text')">Enlarge text</button>
             <div v-html="post.content"></div>
         </div>`
}) 

示例代碼:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <script>
                      
        </script>
	</head>
	<body>
        <h4>16-子組件事件捕獲</h4>
        <div id="app">
            <div :style="{fontSize: postFontSize + 'em'}">
                <!-- 
                    參數說明:
                        v-for:循環父組件的posts屬性
                        key: 唯一表示每個item
                        post:父組件傳遞給子組件的參數,該名字與子組件的post屬性相同
                        v-on:定義一個監聽器,該監聽器用來監聽enLarge-text事件。
                            有了該事件,父組件就會接收該事件並更新postFontSize屬性
                -->
                <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post"
                    v-on:enlarge-text="postFontSize += 0.1"></blog-post>
            </div>
        </div>
        <script>
            // 子組件        
            Vue.component('blog-post', {
                props: ['post'],
                template:  // $emit方法傳入事件名稱來觸發一個事件
                    `<div class="blog-post">
                        <h3>{{post.title}}</h3>
                        <button @click="$emit('enlarge-text')">Enlarge text</button>
                        <div v-html="post.content"></div>
                    </div>`
            }) 

            // 父組件
            let vue = new Vue({ 
                el: '#app',
                data: {
                    posts: [
                        { id: 1, title: 'My journey with Vue', content: 'this is content' },
                        { id: 2, title: 'Blogging with Vue', content: 'this is content' },
                        { id: 3, title: 'Why Vue is so fun', content: 'this is content' }
                    ],
                    postFontSize: 1
                }
            })
        </script>
	</body>
</html>

3.12.4 vmodel在組件中的使用

使用自定義事件處理v-model的雙向綁定。一般用於子組件中的輸入框與父組件中的屬性雙向綁定。

需求:在vue實例中定義searchText屬性,然後在子組件中定義一個input搜索框,搜索框內容發生變化的時候,改變vue實例的searchText屬性的值。

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
	</head>
	<body>
        <h4>17-vmodel在組件中的應用</h4>
        <div id="app">
            <!-- 
                在組件中使用v-model就相當於:
                <custom-input v-bind:value="searchText"
                    v-on:input="searchText = $event"></custom-input>

                上面代碼執行了兩個操作:
                1)v-bind:value 實現父組件的searchText參數與子組件value屬性之間的數據綁定 
                2)v-on:input 定義一個監聽器,該監聽器用來監聽input事件。當子組件中的input內容發生改變,
                    那麼就會就會把新的內容($event)設置到父組件的searchText參數中。
            -->
            <custom-input v-model="searchText"></custom-input>
            {{searchText}}
        </div>
        <script>

            // 子組件
            Vue.component('custom-input', {
                props: ['value'],
                // v-on:input用於監控用戶輸入,當input事件被觸發的時候,
                // 將新的值($event.target.value)通過自定義的input事件拋出
                template: `
                    <input v-bind:value="value" v-on:input="$emit('input', $event.target.value)" />
                `
            })

            // 父組件
            let vue = new Vue({ 
                el: '#app',
                data: {
                    searchText: '呵呵'
                }
            })
        </script>
	</body>
</html>

3.13 插槽

插槽:子組件中的模板接口,它可以在父組件中填充子組件的模板。

定義插槽:

<slot></slot>

示例代碼:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <script>
                      
        </script>
	</head>
	<body>
        <h4>18-插槽</h4>
        <div id="app">
            <alert-box>
                Something bad happened.
            </alert-box>
        </div>
        <script>
            // 子組件
            Vue.component('alert-box', {
                template: `
                    <div class="demo-alert-box">
                        <strong>Error!</strong>
                        <slot></slot>
                    </div>
                `
            })

            // 父組件
            let vue = new Vue({ 
                el: '#app'
            })
        </script>
	</body>
</html>

3.14 動態組件

當組件的內容不確定時,使用動態組件技術選擇加載的組件。例如:選擇Posts的時候顯示Posts組件,選擇Archive時候顯示Archive組件。
在這裏插入圖片描述

3.14.1 創建動態組件

第一步:在data對象中定義一個屬性,該屬性指定要加載的組件名;

let vue = new Vue({ 
    el: '#app',
    data: {
        currentComponent: 'component-2'
    }
})

第二步:使用component引用組件。

<component v-bind:is="currentComponent"></component>

上面<component>元素是vue 裏面的一個內置組件,v-bind:is 決定哪個組件被渲染成動態組件。

示例代碼:

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript"></script>
        <script>
                      
        </script>
	</head>
	<body>
        <h4>19-動態組件</h4>
        <div id="app">
            <component v-bind:is="currentComponent"></component>
        </div>
        <script>
            // 子組件
            Vue.component('component-1', {
                template: `
                    <h3>組件1...</h3>
                `
            })

            Vue.component('component-2', {
                template: `
                    <h3>組件2...</h3>
                `
            })

            // 父組件
            let vue = new Vue({ 
                el: '#app',
                data: {
                    currentComponent: 'component-2'
                }
            })
        </script>
	</body>
</html>

3.14.2 動態組件緩存問題

在這裏插入圖片描述
當在這些組件之間切換的時候,你有時會想保持這些組件的狀態,以避免反覆重渲染導致的性能問題。這時候可以使用<keep-alive>標籤。使用<keep-alive>修飾的組件會保持在內存中,下次使用組件時候直接顯示,避免重新渲染的問題。

<!-- 失活的組件將會被緩存!-->
<keep-alive>
  <component v-bind:is="currentTabComponent"></component>
</keep-alive>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章