[Vuejs]-Leveraging the v-for loop for places outside the v-for

0đź‘Ť

You can try using a custom HTML tag (not registered as a component for Vue), it’s quite “ugly” but that is the only solution I could think of (beware of Vue’s warnings if not disabled) :

<template>
  <div id="app">
    <uglyTag v-for="(sell,index) in sales" :key="index">
      {{sell[ sell.findIndex( e=>e.salesPerson==="bar" ) ].sellValue}}
      <p>{{ sell.sellValue }}</p>
    </uglyTag>
  </div>
</template>

Another solution would be to rethink the construction of your data so you could have (but still needs the uglyTag method) :

data(){
  return {
    salesTitle: 2,
    sales: [
      {
        salesPerson: 'foo',
        sellValue: 1
      },
      {
        salesPerson: 'bar',
        sellValue: 2
      }
    ]
  }
}

and

<template>
  <div id="app">
    <uglyTag v-for="(sell,index) in sales" :key="index">
      {{ salesTitle }}
      <p>{{ sell.sellValue }}</p>
    </uglyTag>
  </div>
</template>

0đź‘Ť

Perhaps I didn’t understand the question correctly, but you are still in the same scope of your component. Why don’t you add a getter for the value you are interested in and display it where you want.

Vue.component('my-template', {
  template: '    <div id="app">\
      <!-- i need to print here the sellValue of \'bar\' -->\
			<p>{{ saleValue }}</p>\
      <p v-for="(sell,index) in sales" :key="index">{{sell.sellValue}}</p>\
    </div>',
  data: function() {
    return {
      sales: [{
        salesPerson: 'foo',
        sellValue: 1
      }, {
        salesPerson: 'bar',
        sellValue: 2
      }]
    }
  },
	computed: {
		saleValue: function() {
			return this.sales.filter(function(val) {
				return val.salesPerson === 'bar';
			})[0].sellValue;
		}
	}
});

var vm = new Vue({
	el: '#vm',
	data: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="vm">
  <my-template></my-template>
</div>

Leave a comment