vue 自定义指令
需求
获取标签,扩展额外的功能
效果
全局 - 自定义指令
代码
// main.js
// 全局指令 - "直接"使用
Vue.directive("gFocus", {
inserted (el) {
console.log(el)
el.focus() // 触发标签的事件方法
}
})
// UseDirective.vue
<template>
<div>
<input type="text" placeholder="请输入" v-gFocus />
</div>
</template>
局部 - 自定义指令
代码
// UseDirective.vue
<template>
<div>
<input type="text" placeholder="请输入" v-pFocus />
</div>
</template>
<script>
export default {
directives: {
pFocus: {
inserted (el) {
el.focus()
}
}
}
}
</script>
自定义命令传值
效果
代码
// main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// 全局指令 - 到处"直接"使用
// 自定义指令传值 - 全局
// inserted方法 - 指令所在标签,被插入到网页上触发
// update方法 - 指令对应数据 / 标签更新时,此方法执行
Vue.directive('color', {
inserted (el, binding) {
console.log(binding)
el.style.color = binding.value
},
update (el, binding) {
el.style.color = binding.value
},
})
new Vue({
render: h => h(App),
}).$mount('#app')
// UseDirective.vue
<template>
<div>
<input type="text" placeholder="请输入" v-pFocus />
<p v-color="colorStr">修改文字颜色</p>
</div>
</template>
<script>
export default {
data () {
return {
colorStr: 'red'
}
},
// 自定义指令传值 - 局部
directives: {
pFocus: {
inserted (el) {
el.focus()
}
}
}
}
</script>
问点
-
inserted 方法 - 指令所在标签,被插入到网页上触发
-
update 方法 - 指令对应数据 / 标签更新时,此方法执行