这篇文章主要介绍“vue3自定义指令的方法是什么”,在日常操作中,相信很多人在vue3自定义指令的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”vue3自定义指令的方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
vue 官方提供了 v-for、v-model、v-if 等常用的内置指令。除此之外 vue 还允许开发者自定义指令。
vue 中的自定义指令分为两类,分别是:
私有自定义指令
全局自定义指令
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令。示例代码如下:
<script>
export default {
directives: {
// 自定义私有指令focus,在使用的时候要用 v-focus 。
focus: {
mounted(el) {
el.focus()
},
},
},
}
</script>
在使用自定义指令时,需要加上 v- 前缀。示例代码如下:
<!-- 声明自定义私有指令focus,在使用的时候要用 v-focus 。 -->
<input v-focus/>
全局共享的自定义指令需要通过“单页面应用程序的实例对象”进行声明,示例代码如下:
import { createApp } from 'vue'
const app = createApp({
/* ... */
})
// 注册(对象形式的指令)
app.directive('my-directive', {
/* 自定义指令钩子 */
})
// 注册(函数形式的指令)
app.directive('my-directive', () => {
/* ... */
})
// 得到一个已注册的指令
const myDirective = app.directive('my-directive')
mounted 函数只在元素第一次插入 DOM 时被调用,当 DOM 更新时 mounted 函数不会被触发。 updated 函数会在每次 DOM 更新完成后被调用。示例代码如下:
// 声明全局自定义指令
app.directive('focus', {
mounted(el) {
console.log('mounted')
el.focus()
},
updated(el) {
console.log('updated')
el.focus()
},
})
注意:在 vue2 的项目中使用自定义指令时,【 mounted 要换成 bind 】【 updated 要换成 update 】
如果 mounted 和updated 函数中的逻辑完全相同,则可以简写成如下格式:
app.directive('focus', (el) => {
// 在 mounted 和 updated 都会触发这个函数方法
el.focus()
})
在绑定指令时,可以通过“等号”的形式为指令绑定具体的参数值,示例代码如下:
// 自定义 v-color 指令
app.directive('color', (el, binding) => {
// binding.value 就是通过 = 绑定的值,在传值的时候传到这 binding.value
el.style.color = binding.value
})
该例子没有特别的技术难点。只是为了验证一下这两天学习的vue3部分知识点,存粹是一个练手记录~~~
//示例
<template>
<p>
改变方向:<input type="text" v-model="direction" />
</p>
<p>
改变数值:<input type="range" min="0" :max="maxNum" v-model="pinPadding" />
</p>
<p>
<button @click="reset">重置</button>
</p>
<div >
<p v-pin:[direction]="pinPadding">数据:{{pinPadding}},方向:{{direction}}</p>
</div>
</template>
<script>
import two from './components/two.vue'
import {
ref,
reactive,
defineComponent,
computed
} from 'vue'
export default ({
name: 'lycApp',
components: {
two
},
setup(prop, context) {
const direction = ref('left')
const pinPadding = ref(0)
const reset = () => {
direction.value = 'left'
pinPadding.value = 0
}
const maxNum = computed(()=>{
if(direction.value == 'right' || direction.value == 'left'){
return 650
}else{
return 360
}
})
return {
direction,
pinPadding,
reset,
maxNum
}
},
directives: {
pin: {
mounted(el, binding) {
el.style.position = 'absolute'
const s = binding.arg
el.style[s] = binding.value + 'px'
},
updated(el, binding) {
el.removeAttribute('style')
el.style.position = 'absolute'
const s = binding.arg
el.style[s] = binding.value + 'px'
}
}
}
})
</script>
到此,关于“vue3自定义指令的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。