Vue.js(16)之 directive

本文深入讲解Vue中的指令使用,包括全局指令与私有指令的定义方式,以及bind和inserted方法的区别。通过具体案例演示如何利用指令实现样式和行为的定制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

推荐阅读:Vue.directive基础,在Vue模块开发中使用

全局指令

Vue.directive('全局自定义指令名称', { /* 自定义指令配置对象 */ })

私有指令

<template></template>

<script>
    export default {
        directives: {
            '私有自定义指令名称': { /* 私有自定义指令配置对象 */ }
        }
    }
</script>

指令配置对象中 bindinserted 的区别

  • bind 方法:

    • 绑定当前指令的元素,在内存中被创建的时候就会被立即调用;指令所绑定到的元素,还没有被插入父节点中;

    • 推荐把样式相关的设置,都定义在 bind 方法中;

  • inserted 方法:

    • 绑定当前指令的元素,被插入到DOM树之后才会被调用;当指令所绑定到的元素,被插入到文档中的父节点时候,会立即触发 inserted 方法

    • 推荐把行为相关的设置,都定义在 inserted 方法中;

  • 演示 bind 和 inserted 的区别:

    • 在终端中打印 el.parentNode 即可

案例

index.js

import Vue from 'vue'

// 自定义指令的名称,在定义的时候,不需要加 v- 前缀,但是在使用的时候,需要加 v- 前缀
Vue.directive('red', {
  // 当指定被第一解析的时候,就会触发 bind 方法,此时,指令所绑定到的元素,还没有被插入父节点中;
  bind: function(el) {
    el.style.color = 'red'
  }
})

Vue.directive('blue', {
  bind: function(el) {
    el.style.color = 'blue'
    // console.log(el.parentNode)
  }
})

Vue.directive('color', {
  bind: function(el, binding) {
    // binding 是指令所绑定的一些数据,其中,binding.value 就是指令 = 后面的数据
    // console.log(binding.value)
    el.style.color = binding.value
  }
})

// 自动获取焦点的指令
Vue.directive('focus', {
  bind: function(el) {
    // 通过 原生DOM对象的 focus 方法,可以让文本框自动获取焦点
    // el.focus()
    console.log('bind方法中打印如下:', el.parentNode)
  },
  // 当指令所绑定到的元素,被插入到文档中的父节点时候,会立即触发 inserted 方法
  inserted: function(el) {
    console.log('inserted方法中打印如下:', el.parentNode)
    el.focus()
  }
})

import app from './app.vue'
const vm = new Vue({
  el: '#app',
  render: c => c(app)
})

app.vue

<template>
  <div>
    <h1 v-red>App根组件</h1>
    <my-home></my-home>
    <hr>
    <my-movie></my-movie>
  </div>
</template>

<script>
// 导入自己的私有组件
import Home from './Home.vue'
import Movie from './Movie.vue'

export default {
  components: {
    'my-home': Home,
    'my-movie': Movie
  }
}
</script>

 

转载于:https://www.cnblogs.com/houfee/p/10036242.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值