【问题标题】:Vue2: Avoid mutating a prop directly inside componentVue2:避免直接在组件内部改变道具
【发布时间】:2017-11-11 13:57:33
【问题描述】:

在检查人员输入是否应该得到一个无效的类时,我得到了这个“避免直接改变一个道具”。

<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

    }
  }
})

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    您收到该警告是因为您通过v-modelpersons 绑定到模板中的输入。因此,更改输入的值将更改 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" ... />
    

    【讨论】:

    • 好的,但是我怎样才能将 srx 元素动态地用于其他元素,然后是“persons”?
    • 传递一个不同的变量作为persons 属性:jsfiddle.net/gsxzz7Ls/1
    • 但是输入元素具有相同的 id 和名称。通过 POST 传递它们时,它们必须具有单独的名称。
    • 传入name 属性并将其绑定到输入的nameid 属性:jsfiddle.net/3a23bbLw
    • 好的,知道了。谢谢!
    猜你喜欢
    • 2018-03-05
    • 2019-11-07
    • 2017-11-28
    • 2020-06-23
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2018-11-26
    • 2021-06-18
    相关资源
    最近更新 更多