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
那完美工作,感谢。 –