Javascript vue js计算方法
我对Vue和Js非常陌生,对计算方法有点困惑。因此,如下所示,我创建了一个道具来共享来自父组件的数据。一切正常,但当sumTotal方法作为默认值执行时,{{sumTotal}上显示Nan。我想知道如何将int 0作为sumTotal值的默认值呈现Javascript vue js计算方法,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我对Vue和Js非常陌生,对计算方法有点困惑。因此,如下所示,我创建了一个道具来共享来自父组件的数据。一切正常,但当sumTotal方法作为默认值执行时,{{sumTotal}上显示Nan。我想知道如何将int 0作为sumTotal值的默认值呈现 //parent component <my-colors :myProp="selectedShape.price"></my-colors> </template> <script
//parent component
<my-colors :myProp="selectedShape.price"></my-colors>
</template>
<script>
import Colors from './Colors.vue';
export default {
data() {
return {
selectedShape: {},
shapes: [{
id: 1,
name: "Square",
price: 4,
}, {
id: 2,
name: "Circle",
price: 6,
}]
}
},
computed: {
totalShape: function() {
var totalShape = 0;
for (var i = 0; i < this.shapes.length; i++) {
if (this.shapes[i].selected) {
totalShape += this.shapes[i].price;
}
}
return totalShape;
}
},
methods: {
getSelectedShape() {
return this.selectedShape;
},
}
}
</script>
//child component
<v-layout row v-for="color in colors" :key="color.id">
<v-layout >
<v-flex >
<v-checkbox class="text-xs-right" name="checkbox" v-bind:label="`${color.name}`" v-model="color.checked" light></v-checkbox>
</v-flex>
</v-layout>
<v-layout column>
<v-flex >
<v-subheader>{{color.price}} €</v-subheader>
</v-flex>
</v-layout>
<v-subheader> {{sumTotal}} €</v-subheader>
</v-layout>
<script>
export default {
props: ['myProp'],
data: () => ({
colors: [{
id: 1,
name: "White",
price: 5,
}, {
id: 2,
name: "Green",
price: 4,
}, {
id: 3,
name: "Blue",
price: 3,
}, {
id: 4,
name: "Red",
price: 2,
}, {
id: 5,
name: "Purple",
price: 1,
}, {
id: 6,
name: "Yellow",
price: 0,
}],
}),
computed: {
total: function() {
var total = 0;
for (var i = 0; i < this.colors.length; i++) {
if (this.colors[i].checked) {
total += this.colors[i].price;
}
}
return total;
},
sumTotal: function() {
var myProp = 0;
return this.total + this.myProp;
}
},
}
</script>
//父组件
从“/Colors.vue”导入颜色;
导出默认值{
数据(){
返回{
selectedShape:{},
形状:[{
id:1,
名称:“广场”,
价格:4,
}, {
id:2,
名称:“圆圈”,
价格:6,
}]
}
},
计算:{
totalShape:function(){
var-totalShape=0;
对于(var i=0;i({
颜色:[{
id:1,
名称:“白色”,
价格:5,,
}, {
id:2,
名称:“绿色”,
价格:4,
}, {
id:3,
名称:“蓝色”,
价格:3,
}, {
id:4,
名称:“红色”,
价格:2,,
}, {
id:5,
名称:“紫色”,
价格:1,,
}, {
id:6,
名称:“黄色”,
价格:0,,
}],
}),
计算:{
总计:函数(){
var合计=0;
for(var i=0;i
当子组件第一次呈现时,父组件的数据属性selectedShape
等于{}
,因此传递给子组件的selectedShape.price
属性将未定义
,并且在调用sumTotal
方法时,它返回someNumber+undefined
,即NaN
要解决此问题,应将默认值price
设置为selectedShape
属性:
selectedShape: { price: 0}
或者您可以更改您的sumTotal
:
sumTotal: function() {
return this.total + (this.myProp || 0);
}
你把什么叫做“我的道具”?@Xlee我已经更新了帖子。谢谢这个.total+
selectedShape.price
~=this.total+undefined==NAN?@Xlee它也将NAN作为默认值呈现…默认值是什么意思selectedShape
是空的{}。