什么是从指令改变道具的正确方法?

时间:2018-03-16 06:09:12

标签: javascript vue.js vuejs2 vue-component

my-component具有error属性。我想从我的指令中专门针对绑定不存在的时候改变该属性。

<my-component
    v-bind:error="things.error"
    v-my-custom-directive>
</my-component>

<my-component
    v-my-custom-directive>
</my-component>

所以我有我的指示:

Vue.directive('my-custom-directive', {
    bind: function(el, binding, vnode) {
        const stuff = '' //work
        vnode.componentInstance.$props.error = stuff;        
    }
}

这会导致以下错误:

Avoid mutating a prop directly

1 个答案:

答案 0 :(得分:2)

我无法辨别出你的目的的所有具体细节,但它是否适合你的目的是免除道具,而是在你的组件中使用$on事件监听器,$ $从你的组件中发出事件指令?

在您的组件中:

data(){
  return{
    error: null
 }
},
created(){
  this.$on('error', function(error){
    this.error = error;
 });
}

在你的指令中:

Vue.directive('my-custom-directive', {
   bind: function(el, binding, vnode) {
       const stuff = 'Has error' //work
       vnode.componentInstance.$emit('error', stuff);        
   }
})

在这里查看我的jfiddle https://jsfiddle.net/skribe/mL18fb2x/