【问题标题】:Update data attribute on component from parent - Vue2 js从父级更新组件的数据属性 - Vue2 js
【发布时间】:2018-03-06 06:17:00
【问题描述】:

我正在尝试创建动态的 Vue 组件来跟踪它们自己的错误状态。 我需要在父组件上进行验证,并且父验证方法应该更新子组件的错​​误状态。 在这个阶段我无法猜测会生成多少子组件,因此很难通过 props 跟踪。将被渲染的子组件的数量是通过 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

【问题讨论】:

    标签: javascript vuejs2


    【解决方案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">
    

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2017-10-20
      • 2019-05-02
      • 2018-04-22
      • 2017-06-13
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多