前端-Vue自定义指令
目录
一.什么是自定义指令
二.使用方法
1.全局定义
2.局部定义
三.自定义指令-指令的值
每个指令有着自己各自独立的功能
一.什么是自定义指令
Vue 的自定义指令是一种可以直接操作 DOM 元素 的机制,适用于那些 v-model
、v-show
、v-if
这些现成指令不好满足的场景。
例子:
比如你想让一个元素自动获得焦点,你可以这样写一个自定义指令:
Vue.directive('focus', {inserted(el) {el.focus()}
})
然后在模板中使用它:
<input v-focus />
二.使用方法
1.全局定义
// 全局注册
Vue.directive('指令名称', {//当前指令所绑定的元素在添加到页面后会自动调用inserted(el) {//el就是指令所绑定的元素console.log(el)}
})
// 文件核心作用:导入App.vue.基于App.vue创建结构渲染index.html
// 1.导入Vue核心包
import Vue from 'vue'
// 2.导入App.vue跟组件
import App from './App.vue'// 3.是否提示当前处于什么环境(生成环境/开发环境)
Vue.config.productionTip = false// 全局注册
Vue.directive('focus', {inserted(el) {console.log(el)}
})// 4.Vue实例化,提供render方法 基于App.vue创建结构渲染index.html
new Vue({// 作用同.$mount('#app')一样,用于指定Vue所管理容器el: '#app',//基于App创建元素结构render: h => h(App),//还有一种写法是// render:(createElement) =>{// return createElement(App)// }
}).$mount('#app')
<script lang="ts">
import {defineComponent} from 'vue'export default defineComponent({name: "GrandfatherComponent",
})
</script><template><div><h1>自定义指令</h1><input v-focus type="text"></div>
</template><style scoped lang="less"></style>
2.局部定义
<script lang="ts">
import {defineComponent} from 'vue'export default defineComponent({name: "GrandfatherComponent",// 局部注册directives: {'focus': {inserted(el) {el.focus()}}},
})
</script><template><div><h1>自定义指令</h1><input v-focus type="text"></div>
</template><style scoped lang="less"></style>
三.自定义指令-指令的值
需求:实现一个color指令-传入不同的颜色,给标签设置文字颜色
语法:
在绑定指令时,可以通过“等号”的形式为指令绑定具体的参数值
<div v-color="color">我是内容<div>
通过binding.value可以拿到指令值,指令值修改会触发update函数
directives: {'color': {inserted(el, binding) {el.style.color = binding.value},update(el, binding) {el.style.color = binding.value}}},
<script lang="ts">
import {defineComponent} from 'vue'export default defineComponent({name: "GrandfatherComponent",// 局部注册directives: {'color': {inserted(el, binding) {el.style.color = binding.value},update(el, binding) {el.style.color = binding.value}}},data() {return {colorOne: '#ff0000',colorTwo: '#5805ff',}}
})
</script><template><div><h1>自定义指令的值</h1><div v-color="colorOne">指令的值</div><div v-color="colorTwo">指令的值</div></div>
</template><style scoped lang="less"></style>