Is it possible to scope in VueJS templates so you don't have to repeat object names when referencing properties?

Viewed 35

I'm porting some code from KnockoutJS to VueJS for an employer and in Knockout they have a with directive that allows object properties to be referenced without repeating the object name.

How do I do this in VueJS? I tried looking into slot scope and template scope and even tried creating my own custom directive that modified the data property on the referenced VNode, but I wasn't able to get it to work.

Current Code:

<div v-for="item in items">
  <div>{{item.name}}</div>
  <div>{{item.phone}}</div>
  <div>{{item.value}}</div>
</div>

Pseudo-code:

<div v-for="item in items" v-with="item">
  <div>{{name}}</div>
  <div>{{phone}}</div>
  <div>{{value}}</div>
</div>

This is purely for readability purposes that I'm asking this as I have already completed the task using the repeated object identifiers when referencing its properties, but I wanted to ask in case there was something that I was missing.

Someone on the VueJS chat rooms suggested using Vuex store, but their sample didn't seem to address my concern of repetitive naming.

1 Answers

You could always destructure your object in the v-for loop, like:

<div v-for="{name, phone} in items">

An example would be:

new Vue({
    data: {
        items: [
            {
                name: 'John',
                phone: '123-456-7890',
                otherVal: 'hello'
            },
            {
                name: 'Joe',
                phone: '234-567-8901',
                otherVal: 'goodbye'
            }
        ]
    }
}).$mount('#demo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">  
  <div v-for="{name, phone} in items">
    {{ name }} {{ phone }}
  </div>  
</div>

Related