Vue.js在computed中获取v-for数组值
Vue.js get v-for array value in computed
我通过Laravel将用户数据传递给组件,该数据包含以英里为单位的距离,但用户可以选择以公里为单位设置视图距离,因此我必须通过profile.dance_mi进行计算,我该如何实现这一点?
HTML:
<saved profiles="{{json_encode($profiles)}}" unit="{{Auth::user()->settings->unit}}"></saved>
<div v-for="profile in profiles" class="col-xs-12 col-sm-4 col-md-3">
...
<h4>@{{distance}}</h4>
....
</div>
JS-
new Vue(
{
el: 'body',
components:
{
saved:
{
template: '#saved',
props: ['profiles', 'unit'],
created: function ()
{
this.profiles = JSON.parse(this.profiles);
},
computed:
{
distance: function ()
{
var unit = this.unit;
return unit == 0 ? Math.round(distance * 1.60934) + ' km' : distance + ' miles';
}
}
}
}
});
像这样的计算属性在组件的for循环中不起作用。
我认为实现您想要实现的目标的最简单方法是制作另一个组件。我有点不清楚你试图观察哪些属性,哪些没有,但我认为这会让你朝着正确的方向前进:
剖面距离分量
var ProfileDistance = Vue.extend({
props: ['profile'],
template: '<span>{{distance}}</span>',
computed: {
distance: function() {
if (this.profile.hasOwnProperty('distance_mi')) {
return this.profile.distance_mi + ' miles away';
} else if(this.profile.hasOwnProperty('distance_km')){
return this.profile.distance_km + ' kilometers away';
} else {
return 'Distance N/A';
}
}
}
})
当然,请确保您在现有的saved
组件中使用该组件
components: {
//....
'profile-distance': ProfileDistance
}
然后将profile
作为属性传递给profile-distance
组件:
<profile-distance :profile="profile"></profile-distance>
这是一个正在工作的jsfiddle
相关文章:
- 在for循环中使用多维数组设置google.maps.Marker图标
- Javascript-用于展开数组的递归/for循环
- JavaScript-将for循环的多个结果推送到数组中
- 将值从for循环(在另一个for循环中)JavaScript中推送到数组
- 使用条件for循环更新数组-Javascript
- 使用for循环填充document.getelementbyid中的数组
- 将推入式数组与for一起使用..在..循环中
- For循环与数组不起作用
- 将数组与For循环进行比较
- 如何在 for 循环中访问 json 数组字段的名称
- 访问带有 for 循环中的计数器的数组
- 使用RegExp循环数组而不是for循环(Javascript)
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?
- for(数组中的i)和for(var i=0;i<array.length;i++)之间的差异
- for (数组中的键)循环遍历数组原型
- Javascript:for(var i<array.length)v.s.for(数组中的e)
- JS:for数组中的每个项的当前值
- 正在使用for…数组的
- Vue.js在computed中获取v-for数组值
- 哪些浏览器支持for..数组上的循环