Vue自定义指令笔记
官网地址: Vue.js
1. 全局自定义指令
自定义指令通过使用 Vue.directive() 定义全局的指令;、
Vue.directive()接受两个参数:
参数1:指令的名称。注意,在定义的时候,指令的名称前面,不需要加 v- 前缀。
但是,在调用的时候,必须在指令名称前加上 v- 前缀来进行调用;
参数2:是一个对象,这个对象身上,有一些指令相关的函数,
这些函数可以在特定的阶段,执行相关的操作。
2. 钩子函数
Vue.directive()的钩子函数有五个,详细可见官网地址:Vue.js
常用的为前三个,bind, inserted, update
Vue.directive('focus', {
bind: function (el) { // 每当指令绑定到元素上的时候,会立即执行这个 bind 函数,只执行一次
// 注意: 在每个 函数中,第一个参数,永远是 el ,表示 被绑定了指令的那个元素,这个 el 参数,是一个原生的JS对象
// 在元素 刚绑定了指令的时候,还没有 插入到 DOM中去,这时候,调用 focus 方法没有作用
// 因为,一个元素,只有插入DOM之后,才能获取焦点
},
inserted: function (el) { // inserted 表示元素 插入到DOM中的时候,会执行 inserted 函数【触发1次】
// 和JS行为有关的操作,最好在 inserted 中去执行,放置 JS行为不生效
},
updated: function (el) { // 当VNode更新的时候,会执行 updated, 可能会触发多次
}
})
简单说明,我们常用bind进行样式修改之类的操作,而在inserted中常进行JS中的有关操作;
钩子函数的参数:可以参照官网,常用为el,binding
el ,表示 被绑定了指令的那个元素,这个 el 参数,是一个原生的JS对象
一个全局自定义指令的例子:(照搬官网)自动获取焦点指令
<input type="text" class="form-control" v-model="keywords" id="search" v-focus v-color="'green'">
----------------------------分割线---------------------------------
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
// 自定义一个 设置字体颜色的 指令
Vue.directive('color', {
// 样式,只要通过指令绑定给了元素,不管这个元素有没有被插入到页面中去,这个元素肯定有了一个内联的样式
// 将来元素肯定会显示到页面中,这时候,浏览器的渲染引擎必然会解析样式,应用给这个元素
bind: function (el, binding) {
// 和样式相关的操作,一般都可以在 bind 执行
el.style.color = binding.value
}
})
3. 自定义私有指令
私有指令使用Vue.directives () ----- //带有s
与全局私有指令相似:
<div id="app">
<h3 v-color="'pink'" v-fontweight="900" v-fontsize="50">{{ dt | dateFormat }}</h3>
</div>
=======================分割线========================
var vm = new Vue({
el: '#app',
data: {},
methods: {},
...
directives: { // 自定义私有指令
'fontweight': { // 设置字体粗细的
bind: function (el, binding) {
el.style.fontWeight = binding.value
}
}
}
})
4. 函数简写
若我们想在 bind 和 update 时触发相同行为,而不关心其它的钩子。上面的例子中增加一个v-fontSize指令
<div id="app">
<h3 v-color="'pink'" v-fontweight="900" v-fontsize="50">{{ dt | dateFormat }}</h3>
</div>
=======================分割线========================
var vm = new Vue({
el: '#app',
data: {},
methods: {},
...
directives: { // 自定义私有指令
'fontweight': { // 设置字体粗细的
bind: function (el, binding) {
el.style.fontWeight = binding.value
}
},
'fontsize': function (el, binding) { // 注意:这个 function 等同于 把 代码写到了 bind 和 update 中去
el.style.fontSize = parseInt(binding.value) + 'px'
}
}
})