Vue的基本認(rèn)識(shí)
官網(wǎng):
英文官網(wǎng): https://vuejs.org/
中文官網(wǎng): https://cn.vuejs.org/
介紹描述
- 漸進(jìn)式 JavaScript 框架
- 作者: 尤雨溪(一位華裔前 Google 工程師)
- 作用: 動(dòng)態(tài)構(gòu)建用戶界面
Vue的特點(diǎn)
- 遵循 MVVM 模式
- 編碼簡(jiǎn)潔, 體積小, 運(yùn)行效率高, 適合移動(dòng)/PC 端開(kāi)發(fā)
- 它本身只關(guān)注 UI, 可以輕松引入 vue 插件或其它第三庫(kù)開(kāi)發(fā)項(xiàng)目
與其它前端 JS 框架的關(guān)聯(lián)
- 借鑒 angular 的模板和數(shù)據(jù)綁定技術(shù)
- 借鑒 react 的組件化和虛擬 DOM 技術(shù)
Vue擴(kuò)展插件
- vue-cli: vue 腳手架
- vue-resource(axios): ajax 請(qǐng)求
- vue-router: 路由
- vuex: 狀態(tài)管理
- vue-lazyload: 圖片懶加載
- vue-scroller: 頁(yè)面滑動(dòng)相關(guān)
- mint-ui: 基于 vue 的 UI 組件庫(kù)(移動(dòng)端)
- element-ui: 基于 vue 的 UI 組件庫(kù)(PC 端)
Vue的基本使用
步驟
- 引入Vue.js
- 創(chuàng)建Vue對(duì)象
el :指定根element(選擇器)
data:初始化數(shù)據(jù)(頁(yè)面可以訪問(wèn)) - 雙向數(shù)據(jù)綁定: v-model
- 顯示數(shù)據(jù):{{xxx}}
- 理解vue的MVVM實(shí)現(xiàn)
示例代碼
<div id="app"> <!--view-->
<input type="text" v-model ="username">
<p>Hello {{username}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
//創(chuàng)建Vue實(shí)例
const vm = new Vue({ //配置對(duì)象
el: '#app', //element:選擇器
data:{ //數(shù)據(jù)(model)
username: 'Hello Vue!'
}
});
</script>
Vue MVVM
- model: 模型,數(shù)據(jù)對(duì)象(data)
- view: 視圖躲履,模板頁(yè)面
- viewModel: 視圖模型(Vue的實(shí)例)
模板語(yǔ)法
模板的理解
- 動(dòng)態(tài)的 html 頁(yè)面
- 包含了一些 JS 語(yǔ)法代碼
a. 雙大括號(hào)表達(dá)式
b. 指令(以 v-開(kāi)頭的自定義標(biāo)簽屬性)
雙大括號(hào)表達(dá)式
- 語(yǔ)法: {{exp}}
- 功能: 向頁(yè)面輸出數(shù)據(jù)
- 可以調(diào)用對(duì)象的方法
指令一: 強(qiáng)制數(shù)據(jù)綁定
- 功能: 指定變化的屬性值
- 完整寫(xiě)法: v-bind:xxx='yyy' //yyy 會(huì)作為表達(dá)式解析執(zhí)行
- 簡(jiǎn)潔寫(xiě)法: :xxx='yyy'
指令二: 綁定事件監(jiān)聽(tīng)
- 功能: 綁定指定事件名的回調(diào)函數(shù)
- 完整寫(xiě)法:
v-on:keyup='xxx'
v-on:keyup='xxx(參數(shù))'
v-on:keyup.enter='xxx' - 簡(jiǎn)潔寫(xiě)法: @keyup='xxx'
@keyup.enter='xxx'
V2.6.0 新增
從 2.6.0 開(kāi)始诞帐,可以用方括號(hào)括起來(lái)的 JavaScript 表達(dá)式作為一個(gè)指令的參數(shù):
<a v-bind:[attributeName]="url"> ... </a>
這里的 attributeName 會(huì)被作為一個(gè) JavaScript 表達(dá)式進(jìn)行動(dòng)態(tài)求值溃卡,求得的值將會(huì)作為最終的參數(shù)來(lái)使用掌猛。例如新啼,如果你的Vue
實(shí)例有一個(gè) data
屬性 attributeName
喝噪,其值為"href"
汰现,那么這個(gè)綁定將等價(jià)于v-bind:href
胶坠。
同樣地君账,你可以使用動(dòng)態(tài)參數(shù)為一個(gè)動(dòng)態(tài)的事件名綁定處理函數(shù):
<a v-on:[eventName]="doSomething"> ... </a>
同樣地,當(dāng) eventName
的值為"focus"
時(shí)沈善,v-on:[eventName]
將等價(jià)于 v-on:focus
乡数。
示例代碼
<div id="app">
<h2>1. 雙大括號(hào)表達(dá)式</h2>
<p>{{content}}</p>
<p>{{content.toUpperCase()}}</p>
<h2>2. 指令一: 強(qiáng)制數(shù)據(jù)綁定</h2>
<a href="url">訪問(wèn)指定站點(diǎn)</a><br>
<a v-bind:href="url">訪問(wèn)指定站點(diǎn)2</a><br>
<a :href="url">訪問(wèn)指定站點(diǎn)2</a><br>
<h2>3. 指令二: 綁定事件監(jiān)聽(tīng)</h2>
<button v-on:click="test">點(diǎn)我</button>
<button @click="test">點(diǎn)我</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
content: 'NBA I Love This Game',
url: 'http://www.baidu.com'
},
methods: {
test () {
alert('好啊!!!')
}
}
})
</script>
計(jì)算屬性和監(jiān)視
計(jì)算屬性
- 在 computed 屬性對(duì)象中定義計(jì)算屬性的方法
- 在頁(yè)面中使用{{方法名}}來(lái)顯示計(jì)算的結(jié)果
監(jiān)視屬性
- 通過(guò)通過(guò) vm 對(duì)象的$watch()或 watch 配置來(lái)監(jiān)視指定的屬性
- 當(dāng)屬性變化時(shí), 回調(diào)函數(shù)自動(dòng)調(diào)用, 在函數(shù)內(nèi)部進(jìn)行計(jì)算
計(jì)算屬性高級(jí)
- 通過(guò) getter/setter 實(shí)現(xiàn)對(duì)屬性數(shù)據(jù)的顯示和監(jiān)視
- 計(jì)算屬性存在緩存, 多次讀取只執(zhí)行一次 getter 計(jì)算
示例代碼
<div id="app">
姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
<!--fullName1是根據(jù)fistName和lastName計(jì)算產(chǎn)生-->
姓名1(單向): <input type="text" placeholder="Full Name1" v-model="fullName1"><br>
姓名2(單向): <input type="text" placeholder="Full Name2" v-model="fullName2"><br>
姓名3(雙向): <input type="text" placeholder="Full Name3" v-model="fullName3"><br>
<p>{{fullName1}}</p>
<p>{{fullName1}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
const vm = new Vue({
el: '#app',
data: {
firstName: 'A',
lastName: 'B',
fullName2: 'A-B'
},
// 計(jì)算屬性配置: 值為對(duì)象
computed: {
fullName1 () { // 屬性的get()
console.log('fullName1()', this)
return this.firstName + '-' + this.lastName
},
fullName3: {
// 當(dāng)獲取當(dāng)前屬性值時(shí)自動(dòng)調(diào)用, 將返回值(根據(jù)相關(guān)的其它屬性數(shù)據(jù))作為屬性值
get () {
console.log('fullName3 get()')
return this.firstName + '-' + this.lastName
},
// 當(dāng)屬性值發(fā)生了改變時(shí)自動(dòng)調(diào)用, 監(jiān)視當(dāng)前屬性值變化, 同步更新相關(guān)的其它屬性值
set (value) {// fullName3的最新value值 A-B23
console.log('fullName3 set()', value)
// 更新firstName和lastName
const names = value.split('-')
this.firstName = names[0]
this.lastName = names[1]
}
}
},
watch: {
// 配置監(jiān)視firstName
firstName: function (value) { // 相當(dāng)于屬性的set
console.log('watch firstName', value)
// 更新fullName2
this.fullName2 = value + '-' + this.lastName
}
}
})
// 監(jiān)視lastName
vm.$watch('lastName', function (value) {
console.log('$watch lastName', value)
// 更新fullName2
this.fullName2 = this.firstName + '-' + value
})
</script>
class與style綁定
理解
- 在應(yīng)用界面中, 某個(gè)(些)元素的樣式是變化的
- class/style 綁定就是專門用來(lái)實(shí)現(xiàn)動(dòng)態(tài)樣式效果的技術(shù)
class綁定
- class='xxx'
- 表達(dá)式是字符串: 'classA'
- 表達(dá)式是對(duì)象: {classA:isA, classB: isB}
- 表達(dá)式是數(shù)組: ['classA', 'classB']
** style綁定**
- :style="{ color: activeColor, fontSize: fontSize + 'px' }"
- 其中 activeColor/fontSize 是 data 屬性
示例代碼
<style>
.classA {
color: red;
}
.classB {
background: blue;
}
.classC {
font-size: 20px;
}
</style>
<div id="demo">
<h2>1. class綁定: :class='xxx'</h2>
<p :class="myClass">xxx是字符串</p>
<p :class="{classA: hasClassA, classB: hasClassB}">xxx是對(duì)象</p>
<p :class="['classA', 'classB']">xxx是數(shù)組</p>
<h2>2. style綁定</h2>
<p :style="{color:activeColor, fontSize}">:style="{ color: activeColor, fontSize: fontSize + 'px' }"</p>
<button @click="update">更新</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
myClass: 'classA',
hasClassA: true,
hasClassB: false,
activeColor: 'red',
fontSize: '20px'
},
methods: {
update () {
this.myClass = 'classB'
this.hasClassA = !this.hasClassA
this.hasClassB = !this.hasClassB
this.activeColor = 'yellow'
this.fontSize = '30px'
}
}
})
</script>
條件渲染
條件渲染指令
-
v-if
與v-else
v-show
比較 v-if 與 v-show
- 如果需要頻繁切換 v-show 較好
- 當(dāng)條件不成立時(shí), v-if 的所有子節(jié)點(diǎn)不會(huì)解析(項(xiàng)目中使用)
示例代碼
<div id="demo">
<p v-if="ok">表白成功</p>
<p v-else>表白失敗</p>
<hr>
<p v-show="ok">求婚成功</p>
<p v-show="!ok">求婚失敗</p>
<button @click="ok=!ok">切換</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
ok: true,
}
})
</script>
列表渲染
列表顯示指令
- 數(shù)組: v-for / index
- 對(duì)象: v-for / key
列表的更新顯示
- 刪除 item
- 替換 item
列表的高級(jí)處理
- 列表過(guò)濾
- 列表排序
示例代碼
<div id="demo">
<h2>測(cè)試: v-for 遍歷數(shù)組</h2>
<ul>
<li v-for="(p, index) in persons" :key="index">
{{index}}--{{p.name}}--{{p.age}}
--<button @click="deleteP(index)">刪除</button>
--<button @click="updateP(index, {name:'Cat', age: 16})">更新</button>
</li>
</ul>
<button @click="addP({name: 'xfzhang', age: 18})">添加</button>
<h2>測(cè)試: v-for 遍歷對(duì)象</h2>
<ul>
<li v-for="(item, key) in persons[1]" :key="key">{{key}}={{item}}</li>
</ul>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
]
},
methods: {
deleteP (index) {
this.persons.splice(index, 1) // 調(diào)用了不是原生數(shù)組的splice(), 而是一個(gè)變異(重寫(xiě))方法
// 1. 調(diào)用原生的數(shù)組的對(duì)應(yīng)方法
// 2. 更新界面
},
updateP (index, newP) {
console.log('updateP', index, newP)
// this.persons[index] = newP // vue根本就不知道
this.persons.splice(index, 1, newP)
// this.persons = []
},
addP (newP) {
this.persons.push(newP)
}
}
})
</script>
<div id="demo">
<input type="text" v-model="searchName">
<ul>
<li v-for="(p, index) in filterPersons" :key="index">
{{index}}--{{p.name}}--{{p.age}}
</li>
</ul>
<div>
<button @click="setOrderType(2)">年齡升序</button>
<button @click="setOrderType(1)">年齡降序</button>
<button @click="setOrderType(0)">原本順序</button>
</div>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
searchName: '',
orderType: 0, // 0代表不排序, 1代表降序, 2代表升序
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
]
},
computed: {
filterPersons () {
// debugger
// 取出相關(guān)數(shù)據(jù)
const {searchName, persons, orderType} = this
let arr = [...persons]
// 過(guò)濾數(shù)組
if(searchName.trim()) {
arr = persons.filter(p => p.name.indexOf(searchName)!==-1)
}
// 排序
if(orderType) {
arr.sort(function (p1, p2) {
if(orderType===1) { // 降序
return p2.age-p1.age
} else { // 升序
return p1.age-p2.age
}
})
}
return arr
}
},
methods: {
setOrderType (orderType) {
this.orderType = orderType
}
}
})
</script>
事件處理
綁定監(jiān)聽(tīng)
- v-on:xxx="fun"
- @xxx="fun"
- @xxx="fun(參數(shù))"
- 默認(rèn)事件形參: event
- 隱含屬性對(duì)象: $event
事件修飾符
-
.prevent
: 阻止事件的默認(rèn)行為event.preventDefault()
-
.stop
: 停止事件冒泡event.stopPropagation()
按鍵修飾符
- .keycode : 操作的是某個(gè) keycode 值的鍵
- .keyName : 操作的某個(gè)按鍵名的鍵(少部分)
示例代碼
<div id="example">
<h2>1. 綁定監(jiān)聽(tīng)</h2>
<button @click="test1">test1</button>
<button @click="test2('abc')">test2</button>
<button @click="test3('abcd', $event)">test3</button>
<h2>2. 事件修飾符</h2>
<a @click.prevent="test4">百度一下</a>
<div style="width: 200px;height: 200px;background: red" @click="test5">
<div style="width: 100px;height: 100px;background: blue" @click.stop="test6"></div>
</div>
<h2>3. 按鍵修飾符</h2>
<input type="text" @keyup.13="test7">
<input type="text" @keyup.enter="test7">
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#example',
data: {
},
methods: {
test1(event) {
alert(event.target.innerHTML)
},
test2 (msg) {
alert(msg)
},
test3 (msg, event) {
alert(msg+'---'+event.target.textContent)
},
test4 () {
alert('點(diǎn)擊了鏈接')
},
test5 () {
alert('out')
},
test6 () {
alert('inner')
},
test7 (event) {
console.log(event.keyCode)
alert(event.target.value)
}
}
})
</script>
表單輸入綁定
使用 v-model 對(duì)表單數(shù)據(jù)自動(dòng)收集
- text/textarea
- checkbox
- radio
- select
示例代碼
<div id="demo">
<form action="/xxx" @submit.prevent="handleSubmit">
<span>用戶名: </span>
<input type="text" v-model="username"><br>
<span>密碼: </span>
<input type="password" v-model="pwd"><br>
<span>性別: </span>
<input type="radio" id="female" value="女" v-model="sex">
<label for="female">女</label>
<input type="radio" id="male" value="男" v-model="sex">
<label for="male">男</label><br>
<span>愛(ài)好: </span>
<input type="checkbox" id="basket" value="basket" v-model="likes">
<label for="basket">籃球</label>
<input type="checkbox" id="foot" value="foot" v-model="likes">
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label><br>
<span>城市: </span>
<select v-model="cityId">
<option value="">未選擇</option>
<option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option>
</select><br>
<span>介紹: </span>
<textarea rows="10" v-model="info"></textarea><br><br>
<input type="submit" value="注冊(cè)">
</form>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
username: '',
pwd: '',
sex: '男',
likes: ['foot'],
allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}],
cityId: '2',
info: ''
},
methods: {
handleSubmit () {
console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
alert('提交注冊(cè)的ajax請(qǐng)求')
}
}
})
</script>
Vue實(shí)例生命周期
生命周期流程圖
vue生命周期分析
- 初始化顯示
beforeCreate()
created()
beforeMount()
mounted()
- 更新?tīng)顟B(tài):
this.xxx = value
beforeUpdate()
updated()
- 銷毀 vue 實(shí)例:
vm.$destory()
beforeDestory()
destoryed()
常用的生命周期方法
-
created()/mounted()
: 發(fā)送 ajax 請(qǐng)求, 啟動(dòng)定時(shí)器等異步任務(wù) -
beforeDestory()
: 做收尾工作, 如: 清除定時(shí)器
示例代碼
<div id="test">
<button @click="destroyVue">destory vue</button>
<p v-if="isShow">hello vue!</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#test',
data: {
isShow: true
},
mounted () {
// 執(zhí)行異步任務(wù)
this.intervalId = setInterval(() => {
console.log('-----')
this.isShow = !this.isShow
}, 1000)
},
beforeDestroy() {
console.log('beforeDestroy()')
// 執(zhí)行收尾的工作
clearInterval(this.intervalId)
},
methods: {
destroyVue () {
this.$destroy()
}
}
})
</script>
過(guò)渡&動(dòng)畫(huà)
vue動(dòng)畫(huà)的理解
- 操作 css 的 trasition 或 animation
- vue 會(huì)給目標(biāo)元素添加/移除特定的 class
- 過(guò)渡的相關(guān)類名
xxx-enter-active
: 指定顯示的 transition
xxx-leave-active
: 指定隱藏的 transition
xxx-enter/xxx-leave-to
: 指定隱藏時(shí)的樣式
transition.png
基本過(guò)渡動(dòng)畫(huà)的編碼
- 在目標(biāo)元素外包裹<transition name="xxx">
- 定義 class 樣式
指定過(guò)渡樣式: transition
指定隱藏時(shí)的樣式: opacity/其它
示例代碼
<style>
/*指定過(guò)渡樣式*/
.xxx-enter-active, .xxx-leave-active {
transition: opacity 1s
}
/*指定隱藏時(shí)的樣式*/
.xxx-enter, .xxx-leave-to {
opacity: 0;
}
.move-enter-active {
transition: all 1s
}
.move-leave-active {
transition: all 3s
}
.move-enter, .move-leave-to {
opacity: 0;
transform: translateX(20px)
}
</style>
<div id="demo">
<button @click="show = !show">Toggle</button>
<transition name="xxx">
<p v-show="show">hello</p>
</transition>
</div>
<hr>
<div id="demo2">
<button @click="show = !show">Toggle2</button>
<transition name="move">
<p v-show="show">hello</p>
</transition>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
show: true
}
})
new Vue({
el: '#demo2',
data: {
show: true
}
})
</script>
<style>
.bounce-enter-active {
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-in .5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
<div id="example-2">
<button @click="show = !show">Toggle show</button>
<br>
<transition name="bounce">
<p v-if="show" style="display: inline-block">Lorem</p>
</transition>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: '#example-2',
data: {
show: true
}
})
</script>
過(guò)濾器
理解過(guò)濾器
- 功能: 對(duì)要顯示的數(shù)據(jù)進(jìn)行特定格式化后再顯示
- 注意: 并沒(méi)有改變?cè)镜臄?shù)據(jù), 可是產(chǎn)生新的對(duì)應(yīng)的數(shù)據(jù)
定義和使用過(guò)濾器
- 定義過(guò)濾器
Vue.filter(filterName, function(value[,arg1,arg2,...]){ // 進(jìn)行一定的數(shù)據(jù)處理
return newValue
})
- 使用過(guò)濾器
<div>{{myData | filterName}}</div>
<div>{{myData | filterName(arg)}}</div>
示例代碼
<div id="test">
<h2>顯示格式化的日期時(shí)間</h2>
<p>{{time}}</p>
<p>最完整的: {{time | dateString}}</p>
<p>年月日: {{time | dateString('YYYY-MM-DD')}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script>
<script>
// 定義過(guò)濾器
Vue.filter('dateString', function (value, format='YYYY-MM-DD HH:mm:ss') {
return moment(value).format(format);
})
new Vue({
el: '#test',
data: {
time: new Date()
},
mounted () {
setInterval(() => {
this.time = new Date()
}, 1000)
}
})
</script>
內(nèi)置指令與自定義指令
常用內(nèi)置指令
-
v:text
: 更新元素的textContent
-
v-html
: 更新元素的innerHTML
-
v-if
: 如果為true
, 當(dāng)前標(biāo)簽才會(huì)輸出到頁(yè)面 -
v-else
: 如果為false
, 當(dāng)前標(biāo)簽才會(huì)輸出到頁(yè)面 -
v-show
: 通過(guò)控制display
樣式來(lái)控制顯示/隱藏 -
v-for
: 遍歷數(shù)組/對(duì)象 -
v-on
: 綁定事件監(jiān)聽(tīng), 一般簡(jiǎn)寫(xiě)為@ -
v-bind
: 強(qiáng)制綁定解析表達(dá)式, 可以省略v-bind
-
v-model
: 雙向數(shù)據(jù)綁定 -
ref
: 指定唯一標(biāo)識(shí),vue
對(duì)象通過(guò)$els
屬性訪問(wèn)這個(gè)元素對(duì)象 -
v-cloak
: 防止閃現(xiàn), 與 css 配合:[v-cloak] { display: none }
自定義指令
- 注冊(cè)全局指令
Vue.directive('my-directive', function(el, binding){
el.innerHTML = binding.value.toupperCase()
})
- 注冊(cè)局部指令
directives : { 'my-directive' : {
bind (el, binding) {
el.innerHTML = binding.value.toupperCase()
}
}
}
- 使用指令
v-my-directive='xxx'
示例代碼
<style>
[v-cloak] { display: none }
</style>
<div id="example">
<p v-cloak>{{content}}</p>
<p v-text="content"></p> <!--p.textContent = content-->
<p v-html="content"></p> <!--p.innerHTML = content-->
<p ref="msg">abcd</p>
<button @click="hint">提示</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#example',
data: {
content: '<a
},
methods: {
hint () {
alert(this.$refs.msg.innerHTML)
}
}
})
</script>
<div id="test">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<div id="test2">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
// 注冊(cè)一個(gè)全局指令
// el: 指令所在的標(biāo)簽對(duì)象
// binding: 包含指令相關(guān)數(shù)據(jù)的容器對(duì)象
Vue.directive('upper-text', function (el, binding) {
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
})
new Vue({
el: '#test',
data: {
msg: "I Like You"
},
// 注冊(cè)局部指令
directives: {
'lower-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toLowerCase()
}
}
})
new Vue({
el: '#test2',
data: {
msg: "I Like You Too"
}
})
</script>
自定義插件
- Vue 插件是一個(gè)包含 install 方法的對(duì)象
- 通過(guò) install 方法給 Vue 或 Vue 實(shí)例添加方法, 定義全局指令等
示例代碼
(function (window) {
const MyPlugin = {}
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或?qū)傩? Vue.myGlobalMethod = function () {
console.log('Vue函數(shù)對(duì)象的myGlobalMethod()')
}
// 2. 添加全局資源
Vue.directive('my-directive',function (el, binding) {
el.textContent = 'my-directive----'+binding.value
})
// 4. 添加實(shí)例方法
Vue.prototype.$myMethod = function () {
console.log('vm $myMethod()')
}
}
window.MyPlugin = MyPlugin
})(window)
<div id="test">
<p v-my-directive="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="vue-myPlugin.js"></script>
<script type="text/javascript">
// 聲明使用插件(安裝插件: 調(diào)用插件的install())
Vue.use(MyPlugin) // 內(nèi)部會(huì)調(diào)用插件對(duì)象的install()
const vm = new Vue({
el: '#test',
data: {
msg: 'HaHa'
}
})
Vue.myGlobalMethod()
vm.$myMethod()
new Object()
</script>