怎么写一个全局的自定义指令

官网例子的延伸https://cn.vuejs.org/v2/guide/custom-directive.html
1.先建立一个directive的文件,在地下建立子文件,例如focus.focus底下有index.js

import Vue from 'vue'
const focus = Vue.directive('focus', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: function(el) {
        // 聚焦元素
        console.log(el, 'el');

        el.focus()
    }
})
export default focus

2.在组件里面去引入和使用

<template>
  <div>
    <p>Hi from {{ name }}</p>
    <NLink to="/">
      Home page ---我是about
    </NLink>
    <!-- 使用自定义指令 -->
    <input type="text" v-focus> 
  </div>
</template>
 
<script>
import focus from '../directive/focus'  //使用自定义指令
export default {
  loading: false,
  directives: { focus }, //使用自定义指令
  asyncData () {
    return {
      name: process.static ? 'static' : (process.server ? 'server' : 'client')
    }
  },
  head: {
    title: 'About page'
  },
  created() {
    console.log(this.$route.params, 'this.$route'); 
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/antyhouse/p/12552092.html