Vue3.0 directive的使用说明

1. 指令生命周期关键字变更

  • 在3.0中指令的注册和其生命周期是这样的
import { createApp } from 'vue'
const app = createApp({})

// 注册
app.directive('my-directive', {
  // Directive has a set of lifecycle hooks:
  // called before bound element's parent component is mounted
  beforeMount() {},
  // called when bound element's parent component is mounted
  mounted() {},
  // called before the containing component's VNode is updated
  beforeUpdate() {},
  // called after the containing component's VNode and the VNodes of its children // have updated
  updated() {},
  // called before the bound element's parent component is unmounted
  beforeUnmount() {},
  // called when the bound element's parent component is unmounted
  unmounted() {}
})
  • 在2.x中指令的注册和其生命周期是这样的
import Vue from 'vue'
// 注册
Vue.directive('my-directive', {
  bind: function () {},
  inserted: function () {},
  update: function () {},
  componentUpdated: function () {},
  unbind: function () {}
})

2. 全局directive

  • 与Vue 2.x的使用方法基本相同
  • 在main.js中添加全局directive。
  • 在3.0中创建vue实例的方式不再是new Vue,而是使用createApp方法进行创建
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.directive('focus', {
    // When the bound element is mounted into the DOM...
    mounted(el) {
        // Focus the element
        console.log(el);
        el.focus()
    }
})
app.mount('#app')
  • 在其他单文件组件调用全局directive
<template>
	<input type="text" name="" id="" v-focus>
</template>

3. 局部使用directive

  • 与Vue 2.x的使用方法基本相同
  • 在单文件组件中使用directive
<template>
	<input type="text" name="" id="" v-focus>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() { return { };},
  directives: {
    focus: {
    	// 参数 el, binding, vnode, oldVnode
    	mounted: function (el) { 
	       el.focus()
	    }
    }
 }
}
</script>
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值