指令:
以 v- 開頭的就是指令
<div v-text="x"></div>
<div v-html="xx"></div>
指令語法:
v- 指令名:參數(shù) = 值 eg. v-on:click = add
- 如果值里沒有特殊字符,則可以不叫引號
- 有些指令沒有參數(shù)和值,如 v-pre (不被編譯)
- 有些指令沒有值,如 v-on:click.prevent
自定義指令:
聲明一個全局指令
// Vue.directive('x',directiveOptions) 任何組件里用 v-x
Vue.directive('x',{
inserted:function(el){
el.addEventListener('click',()=>{console.log('x')})
}
})
聲明一個局部指令
new Vue ({
...,
directives:{
'x':directiveOptions
}
}) //這時v-x只能在該實例中使用
directiveOptions
五個函數(shù)屬性
bind(el,info,vnode,oldVnode) -- 類似 created
inserted(參數(shù)同上) -- 類似 mounted
update(參數(shù)同上) -- 類似 update
unbind(參數(shù)同上) -- 類似 destroyed
v-on2 實現(xiàn)一個簡化版的 v-on
new Vue({
directives:{
on2:{
inserted(el,info){
el.addEventListener(info.arg,info.value)
},
unbind(el,info){
el.removeEventListener(info.arg,info.value)
}
}
}
})
指令的作用:
- 用于DOM操作
Vue實例/組件用于數(shù)據(jù)綁定、事件監(jiān)聽、DOM更新(監(jiān)聽器更新)
Vue指令主要目的就是原生DOM操作(通過DOM API 進行操作)- 減少重復(fù)
如果某個DOM操作比較經(jīng)常使用,就可以封裝成指令
如果某個DOM操作比較復(fù)雜,也可以封裝成指令
常用修飾符:
- @click.stop = "XXX" // 阻止事件傳播/冒泡
- @click.prevent = "XXX" // 阻止默認動作
- @keypress.enter = "XXX" // 鍵盤按下enter事件
- :money.sync = "total" // 語法糖見下文
父子組件傳值規(guī)則:
- 組件不能修改props外部數(shù)據(jù)。
- $emit 可以觸發(fā)事件,并傳參。
-
emit 的參數(shù)。
App.vue
<template>
<div class="app">
班級人數(shù) {{total}}
//<Child :number="total" v-on:addPeople="total = $event"/>
<Child :number="total" v-on:update:number="total = $event"/>//推薦用法
<Child :money.sync="total"/> //vue封裝的一個修飾符,等同于上面的語法
</div>
</template>
<script>
import Child from "./Child.vue"
export default{
data(){
return {total:50};
},
components:{Child}
}
</script>
Child.vue
<template>
<div class="child">
{{number}}
//<button @click="$emit('addPeople', number+1)">
<button @click="$emit('update:number', number+1)">//推薦用法
來了一個插班生
</button>
</div>
</template>
<script>
export default {
props: ["number"]
}
</script>
.sync 修飾符:
一個編譯時的語法糖。它被擴展為一個自動更新父組件屬性的 v-on 監(jiān)聽器
即<Child :number="total" v-on:update:number="total = $event"/> 等價于 <Child :money.sync="total"/>