i try to render page with dynamic properties. my code
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="root"> <div v-for="current in 2" :key="current"> <p :style="currentObject.color"> {{ current }} {{ currentObject.text }} </p> </div> </div>
script is
let vm = new Vue({ el : "#root", created: function () { console.log(this.current) }, data : { current : 0, arrs : [ { color : "background-color: blue;", text : "Dabodee Dabodai" }, { color : "background-color: red;", text : "Angry" }, { color : "background-color: green;", text : "See it works!" } ] }, computed : { currentObject : function() { return this.arrs[this.current]; } } });
i want to p tag with different color and container object text via currentObject but when render the page, computed act likes current is 0 always. output is blue and text from currentObject is “Dabodee Dabodai”
what am i doing wrong?
Advertisement
Answer
Computed property is not the best option here as it will get calculated whenever it changes, meaning that if you iterate through an array the computed value will change on every iteration and at the end you will have all instances with the same value:
What you want is to iterate through your array or access the desired location; so the the most simple approach will work here. As someone already state the for loop will start at 1 so you want to do a -1 to start from the first array location:
<div id="root"> <div v-for="current in 3" :key="current"> <p :style="arrs[current-1].color"> {{ current }} {{ arrs[current-1].text }} </p> </div> </div>
If per the update you want to keep it reactive you can track changes on the arrs value and take an action using a watch to refresh certain item when the array is updated