一 Vue.js是什麼
Vue是一套JavaScript的漸進式框架,可以自底向上逐層應用,Vue的核心庫只關注視圖層,Vue可以將單頁面分割成多個組件幷包含多個html、css、js文件。
二 安裝
.html文件中,cdn引入:
<!-- 開發環境版本,包含了有幫助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生產環境版本,優化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!--原生ES Modules-->
<script type="module">
import Vue from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'
</script>
三 生命週期
四 創建Vue實例
var vm = new Vue({
//api
el: '#example' //綁定html元素,相當於document.getElemnetById('example');
data: {
a: 1
},
created: function(){ //生命週期鉤子函數
console.log('a is' + this.a) //this指vm
}
})
使用vm屬性時,屬性前加$
符號。eg:vm.$el
vm找到id爲example的元素,將data中的值插入,期間執行生命週期函數。
五 模板
1 插值
雙大括號用於文本插值:
<span v-once>Message: {{ msg }}</span>
v-html
用於插入html(易受XSS攻擊)
<span v-html="rawHtml"></span>
模板支持JavaScript表達式。
2 指令
v-
前綴的特殊特性,一些指令可以攜帶參數:
<p v-if="seen">hello</p>
<a v-on:click="toDoFunction">ClickMe</a>
<!--動態參數,attribute可以是Vue實例中的屬性,eg:href,參數名儘量爲小寫-->
<a v-bind:[attribute]="url">...</a>
<!--修飾符,以特定方式綁定-->
<form v-on:submit.prevent="onSubmit">...</form>
3 縮寫
<!-- v-bind 和 v-on -->
<a v-bind:href="url" v-on:click:"doSomething">...</a>
<a :href="url" @click="doSomething">...</a>
六 計算屬性
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
reversedMessage: {
//getter
get: function () {
return this.message.split('').reverse().join('')
},
//setter
set: function(newValue){
return message+newValue.toString()
}
}
}
})
console.log(vm.reversedMessage) //將函數用作屬性的getter函數
結果:
Original message: “Hello”
Computed reversed message: “olleH”
computed是響應式依賴,依賴改變時才重新求值,methods不是。
七 偵聽器
var watchVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'yes'
},
watch: {
question: function(new,old){
this.answer = 'no'
}
}
})
watch
用於監聽數據變化,執行異步操作。