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


官网例子的延伸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>

第二种,全局自定义指令,不用引入直接用
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 在nuxt.config.js
module.exports的底下写入

  plugins: [
        { src: './plugins/proto', ssr: false },
        { src: './directive/focus', ssr: false } // added
    ]

3.直接用

 <div>
        我看看指令行不行哈
        <input type="text" v-focus>
    </div>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM