vue的自定义指令注册使用

2023-12-21 11:26:37

目录

分类

局部注册

全局注册

使用例子


分类

自定义指令的注册分为局部注册全局注册

局部注册是在某个组件内注册的指令,只能在这个组件内使用

全局注册是在main.js中注册的指令在任何组件内都可以使用,指令在使用时不论是全局还是局部注册的,写成v-指令名

比如表单inpu框有focus页面一上来可以自动聚焦

页面一上来就获取焦点,需要借助生命周期mounted,在不使用指令的情况下

要先用ref和$refs获取到dom元素,在执行下面代码

mounted ( ) {
this.$refs.txtRef.focus()
}

mounted()时组件生命周期的挂载后阶段,此阶段可获得渲染后的dom元素

局部注册

例:在App.vue中注册

<template>
  <div>
   <input type="text"  ref="txtRef" v-focus>
  </div>
</template>

<script>
export default {
  // mounted () {
  //   this.$refs.txtRef.focus()
  // }

  directives: {
    focus: {
      inserted (el) {
        el.focus()
      }
    }
  }

}
</script>

<style>

</style>

指令是directives声明的 ,其中el就是指令所在的dom元素

全局注册

在main.js中注册,例如,焦点,字体大小,背景色等

//注册全局指令
Vue.directive('focus', {
  inserted (el) {
    el.focus()
  }
})
//字体大小
Vue.directive('fontsize', {
  inserted (el, binding) {
    el.style.fontSize = binding.value
  },
  update (el, binding) {
    el.style.fontSize = binding.value
  }
})
//背景色
Vue.directive('bgcolor', {
  inserted (el, binding) {
    el.style.backgroundColor = binding.value
  },
  update (el, binding) {
    el.style.backgroundColor = binding.value
  }

})

使用例子

main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

Vue.directive('focus', {
  inserted (el) {
    el.focus()
  }
})
Vue.directive('fontsize', {
  inserted (el, binding) {
    el.style.fontSize = binding.value
  },
  update (el, binding) {
    el.style.fontSize = binding.value
  }
})
Vue.directive('bgcolor', {
  inserted (el, binding) {
    el.style.backgroundColor = binding.value
  },
  update (el, binding) {
    el.style.backgroundColor = binding.value
  }

})

new Vue({
  render: h => h(App)
}).$mount('#app')

App.vue

<template>
  <div>
   <input type="text"  ref="txtRef" v-focus v-bgcolor="'pink'">
   <p v-fontsize="'30px'" v-bgcolor="'skyblue'">梅须逊雪三分白,雪却输梅一段香。</p>
   <header-comp></header-comp>
  </div>

</template>

<script>
import HeaderComp from './components/HeaderComp.vue'
export default {
  components: {
    HeaderComp
  }
  // mounted () {
  //   this.$refs.txtRef.focus()
  // }

  // directives: {
  //   focus: {
  //     inserted (el) {
  //       el.focus()
  //     }
  //   }
  // }

}
</script>

<style>

</style>

HeaderComp.vue

<template>
  <div>

    <input type="text" v-focus>
  </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

效果:

文章来源:https://blog.csdn.net/m0_56713342/article/details/135108762
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。