2017-09-25 20 views
0

我正在尝试创建动态Vue组件,以跟踪其自身的错误状态。 我需要在父组件上进行验证,并且父验证方法应更新子组件错误状态。 在这个阶段,我无法猜测将会生成多少个子组件,因此难以通过道具跟踪。将要呈现的子组件的数量是通过API调用动态确定的。更新父组件的数据属性 - Vue2 js

到目前为止,我发现实现此目的的唯一方法是通过函数参数将组件实例传递给父项,并直接在父组件中更新数据属性。

我的问题是这样的 - 有没有更好的方法来做到这一点,而不是将组件实例作为函数参数传递?

HTML

<div id="app"> 
    <number-only v-for="n in 8" 
       v-on:update="checkNumber"></number-only> 
</div> 

CSS

input { 
    display: block; 
    margin: 5px; 
} 
input.error { 
    border: 1px solid #ff0000; 
    background-color: 
} 

的JavaScript

Vue.component('numberOnly', { 
    template: `<input type="text" 
       :class="{error: hasError}" 
       @keyup="update($event.target.value)" 
       />` 
    , 
    data() { 
    return { 
     hasError: false 
    } 
    }, 
    methods: { 
     update(val){ 
      this.$emit('update', { 
      value: val, 
      instance: this 
      }); 
     } 
     } 
}); 

new Vue({ 
    el: '#app', 
    components: ['numberOnly'], 
    methods: { 
    checkNumber(args){ 
     if(isNaN(args.value)){ 
     args.instance.hasError = true; 
     return; 
     } 
     args.instance.hasError = false; 
    } 
    } 
}); 

这里是一个工作Codepen例如: https://codepen.io/martiensk/pen/wroOLN

回答

1

您可以通过组件的指数作为函数参数:

Vue.component('numberOnly', { 
    props: { 
    index: Number, 
    error: { 
     default: false 
    } 
    }, 
    template: `<input type="text" 
       :class="{error: error}" 
       @keyup="update($event.target.value)" 
       />` 
    , 
    methods: { 
    update(val) { 
     this.$emit('update', val, this.index); 
    } 
    } 
}); 

并给指数和误差参数组成:

HTML

<number-only v-for="n in 8" 
      :index="n" 
      :error="hasError[n]" 
      v-on:update="checkNumber"> 

的JavaScript

new Vue({ 
    el: '#app', 
    components: ['numberOnly'], 
    data() { 
    return { 
     hasError: [], 
    } 
    }, 
    methods: { 
    checkNumber(val, index){ 
     if(isNaN(val)) 
     this.$set(this.hasError, index, true); 
     else 
     this.$set(this.hasError, index, false); 
    } 
    } 
}); 

Code example

或者你也可以直接使用

<number-only v-for="n in 8" 
      :index="n" 
      :class="{'error': hasError[n]}" 
      v-on:update="checkNumber"> 
+0

那完美工作,感谢。 –