javascript - Vue2 : Avoid mutating a prop directly inside component

标签 javascript vue.js vuejs2

在检查人员输入是否应该因为其空而获得无效类时,我得到了这个“避免直接改变 Prop ”。

<script type="text/x-template" id="srx">
  <input type="number" name="persons" id="persons" value="" v-model="persons" :class="{invalid: !persons}">

</script>


<div id="app">
  {{stepText}}
  <sr-el :persons="1"></sr-el>

  <button v-if="currentStep > 1" type="button" v-on:click="previous()">prev</button>
  <button v-if="currentStep < 6" type="button" :disabled="currentStepIsValid()" v-on:click="next()">
    next</button>
</div>

Vue.component('sr-el', {
  template: '#srx',
  props: ['persons'],
})


var App = window.App = new Vue({
  el: '#app',
  data: {
    persons: '1'
    currentStep: 1,
  },
  methods: {
    currentStepIsValid: function() {

      if (this.currentStep == 1) {
        this.stepText = "Step 1;
        return !(this.persons > 0);
      }

    },
    previous: function() {
      this.currentStep = this.currentStep - 1;
      // prev slide
    },

    next: function() {
      this.currentStep = this.currentStep + 1;
      // next slide

    }
  }
})

最佳答案

您收到该警告是因为您通过 v-modelpersons 绑定(bind)到模板中的输入。因此,更改输入的值将更改 persons 的值,这意味着该 prop 会直接在您的 sr-el 组件中发生变化。

您应该设置一个等于 persons 的新属性,并将其传递给 v-model:

Vue.component('sr-el', {
  template: '#srx',
  props: ['persons'],
  data: function() {
    return {
      inputVal: this.persons,
    }
  }
})
<input v-model="inputVal" ... />

关于javascript - Vue2 : Avoid mutating a prop directly inside component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459656/

相关文章:

vue.js - Vuetify - 如何正确验证复选框组

javascript - Jquery UI Slider 不正确的最大值

javascript - Webpack 是否为 Vue 应用程序处理 index.html?

javascript - 如何在 Javascript 中访问事件内部的成员变量

javascript - 通过JS删除HTML的节点

vue.js - 带有 v-for 的 Vue 内联模板 - 未定义

javascript - vue webpack-simple 模板和 Uncaught TypeError : (intermediate value) is not a function

python - 通过 axios 将数据发送到 django rest 框架时获取错误请求 400

javascript - Vue.js 图像 v-for 绑定(bind)

javascript - 为什么这个 promise 没有解决回调用者?