Suppose I have an array of objects in my vue state as shown below:
[ {name: "Daniel", default: false}, {name: "Ross", default: true}, {name: "Rachel", default: false}, {name: "Joey", default: false} {name: "Monica", default: true} {name: "Gunther", default: true} ]
On my web page, all these names are already displayed in the list. What I want to display on the web page is as follows:
From the above example, I think it's pretty clear what I want to achieve. What is the easiest way to achieve this in vue?
P粉7901875072024-03-31 15:33:32
Try using the compulated
attribute. Check the code snippet below
var app = new Vue({ el: '#app', data() { return { list: [ {name: "Daniel", default: false}, {name: "Ross", default: true}, {name: "Rachel", default: false}, {name: "Joey", default: false}, {name: "Monica", default: true}, {name: "Gunther", default: true}, ] }; }, computed: { getList() { let index = 1; return this.list.map(item => { return item.default ? `${item.name} - Default ${index++}` : `${item.name}`; }); } } })
sssccc
- {{item}}
P粉4914214132024-03-31 14:41:07
You can use Array.map to iterate over all array elements and generate the result you want
const data = [ { name: "Daniel" , default: false }, { name: "Ross" , default: true }, { name: "Rachel" , default: false }, { name: "Joey" , default: false }, { name: "Monica" , default: true }, { name: "Gunther", default: true } ]; let defaultCount = 0; const res = data.map(item => `${item.name}${item.default? ` default ${++defaultCount}`:''}`) console.log(res)