【经典】vue2与vue3 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>
    

猜你喜欢

转载自blog.csdn.net/m0_59505309/article/details/127737109