【问题标题】:Vue.js get v-for array value in computedVue.js 在计算中获取 v-for 数组值
【发布时间】:2016-12-12 11:28:12
【问题描述】:

我通过 Laravel 将用户数据传递给组件,该数据包含以英里为单位的距离,但是用户可以选择以公里为单位设置视图距离,因此我必须通过 profile.distance_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';
                    }
                }
            }
        }
    });

【问题讨论】:

    标签: javascript html arrays laravel vue.js


    【解决方案1】:

    这样的计算属性在组件的 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>
    

    here's a working jsfiddle

    【讨论】:

    • profiles数组有一个distance_mi键,user数组有一个unit key,如果unit为0,则用户以KM查看,将miles转换为KM,profiles中没有distance_mi数组,我需要在迭代数组时进行转换,这就是为什么我使用计算属性并将单元传递给 Vue 实例,我只需要获取组件中的距离,我应该从那里开始。
    • 你是对的!毕竟它让我走上了正确的道路!只需要做一个嵌套组件,我刚学Vue,有点复杂,谢谢!有时您需要有人将您设置在正确的行中,嵌套组件和与父级的数据绑定,呵呵!
    • @Jofran 完全理解,大约一周前我自己对 VueJS 完全陌生,但我自己也遇到了类似的问题。很高兴我能帮上忙!
    猜你喜欢
    • 2021-01-17
    • 2018-09-15
    • 2021-06-03
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多