1. Directive 指令
1.1 用 directive 自定义一个指令
Vue.directive("x", {
inserted: function (el) {
el.addEventListener("click", () => {
console.log("x");
});
}
});
通过文档给出的方法创建一个自定义指令 v-x ,这种指令是全局变量,在别的文件也可以使用。
export default {
name: "HelloWorld",
props: {
msg: String,
},
directives: {
x: {
inserted(el) {
el.addEventListener("click", () => {
console.log("x");
});
},
},
},
};
可以写进组件里,但其作用域只在这个组件内部可以使用。
1.2 directive 的五个函数属性(钩子函数)
- bind(el, info/binding, vnode, oldVnode) - 类似 created
- inserted(参数同上) - 类似 mounted
- update(参数同上) - 类似 updated
- componentUpdated(参数同上) - 指令所在组件的 VNode 及其子 VNode 全部更新后调用。用得不多。
- unbind(参数同上) - 类似 destroyed
属性参数:
- el:绑定指令的那个元素
- info:是个对象,用户调用指令时,与指令相关的数据,比如监听什么事件,监听到事件执行什么函数
- vnode:虚拟节点
- oldVnode:之前的虚拟节点
例子:自制一个 v-on2 指令模仿 v-on
Vue.directive("on2", {
inserted(el, info) {
// inserted 可以改为 bind
console.log(info);
el.addEventListener(info.arg, info.value);
// Vue 自带的 v-on 并不是这样实现的,它更复杂,用了事件委托
},
unbind(el, info) {
el.removeEventListener(info.arg, info.value);
}
});
// app.vue
<div v-on2:click="sendLog">这是on2</div>
arg:传给指令的参数,可选。例如 v-on2:click 中,参数为 "click"。
value:指令的绑定值,这里是click中传入的函数。
函数简写
想在 bind 和 update 时触发相同行为,而不关心其它的钩子可以这样写,但是大多数时间写清楚钩子会更加容易阅读和维护。
Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})
1.3 指令的作用
- 主要用于DOM操作
Vue 实例/组件用于数据绑定、事件监听
DOM更新
Vue 指令主要目的就是原生 DOM 操作 - 减少重复
如果某个 DOM 操作经常使用或者比较复杂,可以将其封装为指令
2 mixins 混入
2.1 减少重复
类比
- directives 的作用是减少 DOM 操作的重复
- mixins 的作用是减少 data、methods、钩子的重复
场景描述
假设一种情况,现有五个子组件,都需要监听其组件的created、destroyed时间,并且打印出存活时间。
- 先来思考一下,如何实现监听和获取时间。
// Child1.vue
<template>
<div>Child1</div>
</template>
<script>
export default {
data() {
return {
name: "Child1",
time: undefined,
};
},
created() { // 出生的时候取时间
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="标志位"
设置button开关。
<Child1 v-if="child1Visible" />
<button @click="child1Visible = false">x</button>
- 这样就实现了Child1,其他四个组件也都是一摸一样,所以我们可以创建一个共通文件 ./mixins/log.js 把相同操作全部规整到这里。
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五个组件除了name不同,省去重复代码就可以简化成如下所示。
<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技巧
选项合并
选项智能合并文档
也可以使用全局Vue.mixin 但不推荐使用
3. extends 继承、扩展
extends也是构造选项里的一个选项,跟mixins很像,也是复制减少重复但形式不同。extends更抽象高级,但还是推荐用mixins。
步骤
1.新建文件MyVue.js,这不是Vue组件。
import Vue from "vue"
const MyVue = Vue.extend({ //继承Vue,MyVue就是Vue的一个扩展
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.导入+继承
Child1.vue
<template>
<div>Child1</div>
</template>
<script>
import MyVue from "../MyVue.js";
export default{
extends:MyVue,
data(){
return {
name:"Child1"
}
}
}
</script>
extends是比mixins更抽象一点的封装。如果嫌写5次mixins麻烦,可以考虑extends一次,不过实际工作中用的很少。
4. provide(提供) 和 inject(注入)
举个例子,按下相关按钮改变主题和颜色。
<template>
<div :class="`app theme-${themeName} fontSize-${fontSizeName}`">
<!-- 这里的双引号是XML的双引号,里面的才是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出来的数据inject进这个组件
};
</script>
小结
- 作用:大范围的 data 和 method 等公用
- 注意:不能只传 themeName,不传changeTheme,因为前者是值被复制给了provide。
- 不建议引用修改值,会不清楚这个值被传出去如何修改。
provide() { // 将提供给外部使用的变量provide出去
return {
themeName: {value: this.themeName},
changeTheme: this.changeTheme,
changeFontSize: this.changeFontSize,
};
},
总结
- directives 指令
全局用Vue. directive('x', {...})
局部用options.directives
作用是减少 DOM 操作相关重复代码 - mixins 混入
全局用Vue. mixin({...})
局部用options.mixins:[mixins1, mixins2]
作用是减少 options 里面的重复 - extends 继承/扩展
全局用Vue. extend({...})
局部用options.extends:{...}
作用跟 mixins 差不多,只是形式不同 - provide / inject 提供和注入
祖先提供东西,后代注入东西
作用是大范围、隔N代共享信息