在这里,我有一个名为total_price
的变量,它是从laravel发送的。我想做很多事情。当我使用方法时,当脚本运行它们时,我得到了mutating error
。这是脚本:
export default {
props: {
.//some other props here are cut for better reading
.
.
total_price:{
type:Number
},
.
.
.
},
data(){
return {
newValue:7,
total_price:1,
}
},
我在这样的方法中使用它们:
methods:{
getNotificationClass (notification) {
return `alert alert-${notification.type}`
},
mpminus: function () {
if ((this.newValue) > this.min) {
this.newValue = this.newValue - 1
this.$emit('input', this.newValue)
}
if(this.newValue < this.max_occupancy){
this.total_price = this.extra_price / ( this.newValue - this.base_capacity )
this.person_number =this.newValue - this.base_capacity
this.$emit('input', this.totalprice)
this.$emit('input', this.person_number)
}
},
mpplus: function () {
if (this.max === undefined || (this.newValue < this.max)) {
this.newValue = this.newValue + 1
this.$emit('input', this.newValue)
}
if(this.newValue > this.base_capacity){
this.total_price = this.extra_price * ( this.newValue - this.base_capacity )
this.person_number =this.newValue - this.base_capacity
this.$emit('input', this.totalprice)
this.$emit('input', this.person_number)
}
},
},
...使用此模板:
<div class="minusplusnumber">
<div class="mpbtn minus" v-on:click="mpminus()">
-
</div>
<div id="field_container">
<input type="number" v-model="newValue" disabled />
</div>
<div class="mpbtn plus" v-on:click="mpplus()">
+
</div>
</div>
当我单击minus
或plus
时,出现以下警告:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "total_price"
found in
---> <Reserve> at resources/js/components/Reserve.vue
<Root>
答案 0 :(得分:1)
Here是如何与突变一起使用道具的一个示例-这是总结您要完成的工作的好方法。
只需更改:default-value=X
中的数字即可模拟向下传递道具。
完整链接: https://codepen.io/oze4/pen/PLMEab
HTML:
<!-- Main Vue instance (aka parent) -->
<div id="app">
<!-- ----------------------------------------- -->
<!-- CHANGE THE NUMBER 10 TO WHATEVER YOU WANT -->
<!-- ----------------------------------------- -->
<my-counter :default-value=10></my-counter>
</div>
<!-- Child component as x-template component -->
<script type="text/x-template" id="counter">
<div>
<div style="border: 1px solid black; width: 250px; margin: 40px 40px 40px 40px">
<v-btn @click="increase" color="blue">Increase</v-btn>
<v-btn @click="decrease" color="red">Decrease</v-btn>
</div>
<div>
<div>
<h3 style="margin-left: 40px;">Current Count: {{ currentValue }}</h3>
</div>
</div>
</div>
</script>
JS / Vue
/**
* Child component as x-template
*/
const appCounter = {
template: '#counter',
props: {
defaultValue: {
type: Number,
default: 0
}
},
data() {
return {
currentValue: '',
}
},
mounted() {
this.currentValue = this.defaultValue;
},
methods: {
increase(){
this.currentValue++;
},
decrease(){
this.currentValue--;
}
}
}
/**
* Main Vue Instance
*/
new Vue({
el: "#app",
components: {
myCounter: appCounter
}
});