1. Directive 指令
1.1 用 directive 自定義一個(gè)指令
Vue.directive("x", {
inserted: function (el) {
el.addEventListener("click", () => {
console.log("x");
});
}
});
通過(guò)文檔給出的方法創(chuàng)建一個(gè)自定義指令 v-x ,這種指令是全局變量,在別的文件也可以使用。
export default {
name: "HelloWorld",
props: {
msg: String,
},
directives: {
x: {
inserted(el) {
el.addEventListener("click", () => {
console.log("x");
});
},
},
},
};
可以寫(xiě)進(jìn)組件里,但其作用域只在這個(gè)組件內(nèi)部可以使用。
1.2 directive 的五個(gè)函數(shù)屬性(鉤子函數(shù))
- bind(el, info/binding, vnode, oldVnode) - 類(lèi)似 created
- inserted(參數(shù)同上) - 類(lèi)似 mounted
- update(參數(shù)同上) - 類(lèi)似 updated
- componentUpdated(參數(shù)同上) - 指令所在組件的 VNode 及其子 VNode 全部更新后調(diào)用。用得不多。
- unbind(參數(shù)同上) - 類(lèi)似 destroyed
屬性參數(shù):
- el:綁定指令的那個(gè)元素
- info:是個(gè)對(duì)象,用戶調(diào)用指令時(shí),與指令相關(guān)的數(shù)據(jù),比如監(jiān)聽(tīng)什么事件,監(jiān)聽(tīng)到事件執(zhí)行什么函數(shù)
- vnode:虛擬節(jié)點(diǎn)
- oldVnode:之前的虛擬節(jié)點(diǎn)
例子:自制一個(gè) v-on2 指令模仿 v-on
Vue.directive("on2", {
inserted(el, info) {
// inserted 可以改為 bind
console.log(info);
el.addEventListener(info.arg, info.value);
// Vue 自帶的 v-on 并不是這樣實(shí)現(xiàn)的,它更復(fù)雜,用了事件委托
},
unbind(el, info) {
el.removeEventListener(info.arg, info.value);
}
});
// app.vue
<div v-on2:click="sendLog">這是on2</div>
arg:傳給指令的參數(shù),可選。例如 v-on2:click 中,參數(shù)為 "click"。
value:指令的綁定值,這里是click中傳入的函數(shù)。
函數(shù)簡(jiǎn)寫(xiě)
想在 bind 和 update 時(shí)觸發(fā)相同行為,而不關(guān)心其它的鉤子可以這樣寫(xiě),但是大多數(shù)時(shí)間寫(xiě)清楚鉤子會(huì)更加容易閱讀和維護(hù)。
Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})
1.3 指令的作用
- 主要用于DOM操作
Vue 實(shí)例/組件用于數(shù)據(jù)綁定、事件監(jiān)聽(tīng)
DOM更新
Vue 指令主要目的就是原生 DOM 操作 - 減少重復(fù)
如果某個(gè) DOM 操作經(jīng)常使用或者比較復(fù)雜,可以將其封裝為指令
2 mixins 混入
2.1 減少重復(fù)
類(lèi)比
- directives 的作用是減少 DOM 操作的重復(fù)
- mixins 的作用是減少 data、methods、鉤子的重復(fù)
場(chǎng)景描述
假設(shè)一種情況,現(xiàn)有五個(gè)子組件,都需要監(jiān)聽(tīng)其組件的created、destroyed時(shí)間,并且打印出存活時(shí)間。
- 先來(lái)思考一下,如何實(shí)現(xiàn)監(jiān)聽(tīng)和獲取時(shí)間。
// Child1.vue
<template>
<div>Child1</div>
</template>
<script>
export default {
data() {
return {
name: "Child1",
time: undefined,
};
},
created() { // 出生的時(shí)候取時(shí)間
this.time = new Date();
console.log(`${this.name}出生了`);
},
beforeDestroy() { // 在元素消亡之前取值,所以不能用destroyed
const now = new Date();
console.log(`${this.name}消亡了,共生存了 ${now - this.time} ms`);
},
};
</script>
然后在使用子組件的文件App.vue中,用v-if="標(biāo)志位"設(shè)置button開(kāi)關(guān)。
<Child1 v-if="child1Visible" />
<button @click="child1Visible = false">x</button>
- 這樣就實(shí)現(xiàn)了Child1,其他四個(gè)組件也都是一摸一樣,所以我們可以創(chuàng)建一個(gè)共通文件 ./mixins/log.js 把相同操作全部規(guī)整到這里。
const log = {
data() {
return {
name: undefined,
time: undefined
};
},
created() {
if (!this.name) {
throw new Error("need name");
}
this.time = new Date();
console.log(`${this.name}出生了`);
},
beforeDestroy() {
const now = new Date();
console.log(`${this.name}死亡了,共生存了 ${now - this.time} ms`);
}
};
export default log;
Child五個(gè)組件除了name不同,省去重復(fù)代碼就可以簡(jiǎn)化成如下所示。
<script>
import log from "../mixins/log.js";
export default {
data() {
return {
name: "Child1"
};
},
created() {
console.log("Child 1 的 created");
},
mixins: [log]
};
</script>
2.2 mixins技巧
選項(xiàng)合并
選項(xiàng)智能合并文檔
也可以使用全局Vue.mixin 但不推薦使用
3. extends 繼承、擴(kuò)展
extends也是構(gòu)造選項(xiàng)里的一個(gè)選項(xiàng),跟mixins很像,也是復(fù)制減少重復(fù)但形式不同。extends更抽象高級(jí),但還是推薦用mixins。
步驟
1.新建文件MyVue.js,這不是Vue組件。
import Vue from "vue"
const MyVue = Vue.extend({ //繼承Vue,MyVue就是Vue的一個(gè)擴(kuò)展
data(){ return {name:'',time:undefined} },
created(){
if(!this.name){console.error('no name!')}
this.time = new Date()
},
beforeDestroy(){
const duration = (new Date()) - this.time
console.log(`${this.name} ${duration}`)
},
//mixins:[log] 也可以使用mixins
})
export default MyVue
2.導(dǎo)入+繼承
Child1.vue
<template>
<div>Child1</div>
</template>
<script>
import MyVue from "../MyVue.js";
export default{
extends:MyVue,
data(){
return {
name:"Child1"
}
}
}
</script>
extends是比mixins更抽象一點(diǎn)的封裝。如果嫌寫(xiě)5次mixins麻煩,可以考慮extends一次,不過(guò)實(shí)際工作中用的很少。
4. provide(提供) 和 inject(注入)
舉個(gè)例子,按下相關(guān)按鈕改變主題和顏色。
<template>
<div :class="`app theme-${themeName} fontSize-${fontSizeName}`">
<!-- 這里的雙引號(hào)是XML的雙引號(hào),里面的才是js字符串 -->
<Child1 />
<button>x</button>
</div>
</template>
<script>
import Child1 from "./components/Child1.vue";
export default {
provide() { // 將提供給外部使用的變量provide出去
return {
themeName: this.themeName,
changeTheme: this.changeTheme,
changeFontSize: this.changeFontSize,
};
},
name: "App",
data() {
return {
themeName: "blue", // 'red'
fontSizeName: "normal", // 'big' | 'small'
};
},
components: {
Child1,
},
methods: {
changeTheme() {
if (this.themeName === "blue") {
this.themeName = "red";
} else {
this.themeName = "blue";
}
},
changeFontSize(name) {
if (["big", "nomal", "small"].indexOf(name) >= 0) {
this.fontSizeName = name;
}
},
},
};
</script>
// ChangeThemeButton.vue
<template>
<div>
<button @click="changeTheme">換膚</button>
<button @click="changeFontSize('big')">大字</button>
<button @click="changeFontSize('small')">小字</button>
<button @click="changeFontSize('normal')">正常字</button>
</div>
</template>
<script>
export default {
inject: ["themeName", "changeTheme", "changeFontSize"] // 將App.vue中provide出來(lái)的數(shù)據(jù)inject進(jìn)這個(gè)組件
};
</script>
小結(jié)
- 作用:大范圍的 data 和 method 等公用
- 注意:不能只傳 themeName,不傳changeTheme,因?yàn)榍罢呤侵当粡?fù)制給了provide。
- 不建議引用修改值,會(huì)不清楚這個(gè)值被傳出去如何修改。
provide() { // 將提供給外部使用的變量provide出去
return {
themeName: {value: this.themeName},
changeTheme: this.changeTheme,
changeFontSize: this.changeFontSize,
};
},
總結(jié)
- directives 指令
全局用Vue. directive('x', {...})
局部用options.directives
作用是減少 DOM 操作相關(guān)重復(fù)代碼 - mixins 混入
全局用Vue. mixin({...})
局部用options.mixins:[mixins1, mixins2]
作用是減少 options 里面的重復(fù) - extends 繼承/擴(kuò)展
全局用Vue. extend({...})
局部用options.extends:{...}
作用跟 mixins 差不多,只是形式不同 - provide / inject 提供和注入
祖先提供東西,后代注入東西
作用是大范圍、隔N代共享信息