目录
㋀㏭
☪ 自定义指令 v-x
自定义指令分为局部自定义和全局自定义。
◆ 菜鸟教程
https://www.runoob.com/vue2/vue-custom-directive.html
◆ 局部自定义——directives
不管在哪个文件写的,用属性方式注册的就是局部的。如写在App.vue当中仅仅在其中使用。
➊ directives
.....
},
directives: {
/**
* 每一个指令都是一个方法,指令名在使用的时候要加上v-x
*/
/* 自定义指令-1,binding 标识绑定的变量或者计算表达式,value标识的就是red啥的value*/
color: function(el, binding) {
el.style.color = binding.value;
},
focus:{
inserted:function(el){
el.focus();
}
}
},
methods: {
......
➋ template
<!-- App.vue使用全局指令 -->
<template>
<div>
<!-- 如果已进入input界面就会焦点在最后一个使用v-focus指令的框中 -->
<p v-color="'red'">颜色</p>
<input type="text" v-focus >
</div>
</template>
➌ 效果
◆ 全局自定义——Vue.directive
注意:Vue.directive(‘参数名称’,{}) 定义全局指令,它有两个参数
参数1:指令名称,注意在定义的时候,指令名称前不需要加 v- 前缀,但是在调用的时候,必须加v- 前缀。
参数2:参数2是一个对象,这个对象身上有一些指令相关的函数(也就是下边介绍的钩子函数),这些函数可以在特定的阶段,执行相关操作。
➊ pic
➋ 代码
/* main.js */
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
Vue.directive('color', {
bind: function(el, binding) {
el.style.color = binding.value;
}
})
new Vue({
el: '#app',
/* es6语法 */
/* render:function(h){
return h(App)
} */
render: (h) => h(App),
})
<!-- App.vue使用全局指令 -->
<template>
<div>
<p v-color="'red'">红色</p>
<p v-color="'yellow'">钩子函数的传参</p>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
➌ 效果