Vue.js(16)之 directive自定義指令

推薦閱讀:Vue.directive基礎,在Vue模塊開發中使用html

全局指令

Vue.directive('全局自定義指令名稱', { /* 自定義指令配置對象 */ })

私有指令

<template></template>

<script>
    export default {
        directives: {
            '私有自定義指令名稱': { /* 私有自定義指令配置對象 */ }
        }
    }
</script>

指令配置對象中 bindinserted 的區別

  • bind 方法:vue

    • 綁定當前指令的元素,在內存中被建立的時候就會被當即調用;指令所綁定到的元素,尚未被插入父節點中;app

    • 推薦把樣式相關的設置,都定義在 bind 方法中;post

  • inserted 方法:url

    • 綁定當前指令的元素,被插入到DOM樹以後纔會被調用;當指令所綁定到的元素,被插入到文檔中的父節點時候,會當即觸發 inserted 方法spa

    • 推薦把行爲相關的設置,都定義在 inserted 方法中;code

  • 演示 bind 和 inserted 的區別:component

    • 在終端中打印 el.parentNode 便可htm

案例

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>

相關文章
相關標籤/搜索