gpt4 book ai didi

javascript - Vue2 : Avoid mutating a prop directly inside component

转载 作者:行者123 更新时间:2023-12-01 03:32:35 25 4
gpt4 key购买 nike

在检查人员输入是否应该因为其空而获得无效类时,我得到了这个“避免直接改变 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com