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>