Vue.js(16)之 指令的基本语法

自定义指令

全局指令

语法: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'

// 演示自定义全局指令的语法:
// Vue.directive('自定义指令的名称', { /* 自定义指令的配置对象 */ })
// 自定义指令的名称,在定义的时候,不需要加 v- 前缀,但是在使用的时候,需要加 v- 前缀
Vue.directive('red', {
  // 当指定被第一解析的时候,就会触发 bind 方法,
  // 此时,指令所绑定到的元素,还没有被插入父节点中;
  // 【推荐】在 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
  }
})

// 自动获取焦点的指令
// 总结:推荐在 bind 中对元素的样式进行操作;推荐在 inserted 中对元素的行为进行操作;
Vue.directive('focus', {
  bind: function(el) {
    // 通过 原生DOM对象的 focus 方法,可以让文本框自动获取焦点
    // el.focus()
    console.log('bind方法中打印如下:')
    console.log(el.parentNode)
  },
  // 当指令所绑定到的元素,被插入到文档中的父节点时候,会立即触发 inserted 方法
  inserted: function(el) {
    console.log('inserted方法中打印如下:')
    console.log(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>

猜你喜欢

转载自www.cnblogs.com/houfee/p/10036242.html