鍍金池/ 問答/HTML5  HTML/ 在main.js中定義的多個全局指令不起作用

在main.js中定義的多個全局指令不起作用

這是main.js的代碼:

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
    directives: {
        globalf: function(el,binding){
            el.style.color = binding.value
        },
        globals: function(el,binding){
            el.style.color = binding.value
        }
    }
})
回答
編輯回答
生性

在app.vue中我是這樣調(diào)用的:

clipboard.png
在子組件中我是這樣調(diào)用的:

clipboard.png

教學(xué)視頻中是這樣的:

clipboard.png

而且我按你之前的說話,在app.vue中調(diào)用golbalf也是沒起作用的,也還是會報錯的。

2018年8月28日 14:18
編輯回答
澐染

指令有inserted,update等事件。應(yīng)該寫在那里面

Vue.directive('focus', {
    // 當(dāng)綁定元素插入到 DOM 中。
    inserted: function(el) {
        // 聚焦元素
        if (el.getElementsByTagName('input').length) {
            el.getElementsByTagName('input')[0].focus()
        }
        if (el.getElementsByTagName('textarea').length) {
            el.getElementsByTagName('textarea')[0].focus()
        }
        // el.focus()
    },
    // update: function(el, a, b) {
    //     if (el.className.indexOf('el-select') > -1) {
    //         return
    //     }
    //     setTimeout(() => {
    //         el.getElementsByTagName('input')[0].focus()
    //     }, 200)
    // }
})
2018年4月20日 15:00
編輯回答
悶油瓶

首先區(qū)別你是不是要注冊一個全局指令

Vue.directive('focus', { // 注冊一個全局自定義指令 v-focus
 inserted: function (el) {  // 當(dāng)綁定元素插入到 DOM 中。
    el.focus() // 聚焦元素
 }
})

directive: { //局部指令
 focus(el){
     el.focus()
 }
}
<input v-focus>  // html 使用指令
2017年9月24日 04:26
編輯回答
耍太極

首先,你注冊的并不叫全局指令,只是根組件的指令,屬于局部指令。
如果你的指令是加在了子組件上,肯定會報錯,因為子組件訪問不到。
符合以上情況的話可改為

Vue.directive('color', function (el, banding) {
  el.style.color = banding.value
})

補充一下吧

<div id="app" v-color="'red'">
  red
  <div v-color="'blue'">blue</div>
  <my-component v-color="'yellow'"></my-component>
</div>
  1. v-color="'red'"v-color="'blue'"都屬于父組件的局部指令,而v-color="'yellow'"會報錯。
  2. color樣式是會繼承的。

你再對比對比你的跟他的

2017年10月30日 18:55