Vue.js 2 Object variable within div tag

时间:2018-04-20 01:15:43

标签: vue.js

In view when you have an array you can use the following to get some object and then use it withing that tag.

<div v-for="f in filters">
    {f.minValue}
</div>
<script>
{
  data: {
    filters:[{minValue: "6"},{minValue: "10"}]
  }
}
</script>

Is there an equivalent for just defining an object? e.g.

<div :SOMETHING="filter.filterBetween as tempObject">
     {tempObject.minValue}
</div>
{
  data: {
    filter:{
        filterBetween:{
          minValue: "6",
          maxValue: "10"
          }
      }
  }
}
</script>

Have had a look around but not able to find anything or I'm using the wrong wording to looks for it.

Thanks in advance

3 个答案:

答案 0 :(得分:2)

不幸的是,没有。

使用v-for有一种解决方法,但它有点脏:

<div v-for="tempObject in [filter.filterBetween]">
     {{ tempObject.minValue }}
</div>
<script>
{
  data: {
    filter:{
        filterBetween:{
          minValue: "6",
          maxValue: "10"
          }
      }
  }
}
</script>

看到它的实际效果:

new Vue({
  el: '#app',
  data: {
    filter: {
      filterBetween: {
        minValue: "6",
        maxValue: "10"
      }
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="tempObject in [filter.filterBetween]">
    {{ tempObject.minValue }}
  </div>
</div>

答案 1 :(得分:1)

也许使用计算属性:

&#13;
&#13;
new Vue({
  el: '#app',
  data: {
    filter: {
      filterBetween: {
        minValue: "6",
        maxValue: "10"
      }
    }
  },
  computed: {
    tempObject () { return this.filter.filterBetween }
  }
})
&#13;
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    {{ tempObject.minValue }}
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我不确定我是否完全理解您的问题,但在我看来,您只想绑定到过滤器的minValuemaxValue。如果是这种情况,您真的不需要array(除非您有多个过滤器),并且您并不需要为tempObject设置别名。

我可以建议这种方法。将过滤器定义为对象,并使用您在数组迭代中尝试的相同绑定,而是在valueFilter实例的Vue属性上使用它。

<script>
export default {
  name: 'some-component',
  data() {
    return {
       valueFilter: {
           minValue: 6,
           maxValue: 10
        }
    };
  }
});
</script>
<template>
    <div id="some-component">
      <div>
        from: {{ valueFilter.minValue }} to: {{ valueFilter.maxValue }}
      </div>
    </div>
</template>

您不需要遍历数组来对data中定义的属性进行绑定。并且您不需要computed property,因为您想要显示的值似乎是不变的。

如果您要绑定的对象经常更改,或者它需要某种计算,那么是的,computed属性是合适的,但我认为这不是你真正的试图实现。