javascript - 从父级更新组件上的数据属性 - Vue2 js

标签 javascript vuejs2

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

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

我的问题是 - 有没有比将组件实例作为函数参数传递更好的方法?

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

最佳答案

您可以将组件的索引作为函数参数传递:

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">

关于javascript - 从父级更新组件上的数据属性 - Vue2 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46402473/

相关文章:

javascript - Javascript Plotly 错误 : 'calling plotly as if redrawing but this container doesn' t have a plot yet"

javascript - 如何从 `iframe` 听到内容变化?

javascript - 欢乐 javascript 导入

vue.js - 使用 Vue 测试工具全局模拟数据

javascript - 使用下拉菜单自动填充文本框

javascript - 无法让 Leaflet.Spin 插件在 R Shiny 中工作

vuejs2 - VueJs : Pass Dynamic Components as props to another Component and render them

javascript - Vue JS 如何在脚本中访问数据变量

javascript - 如何将新用户添加到 db.json

javascript - Vuejs组件路由动态选择