C
C
Cyrus2019-06-11 23:18:52
Vue.js
Cyrus, 2019-06-11 23:18:52

How to display titles marked with a checkbox from an array?

Tell me how to display only the titles of the title array marked with a checkbox?

The sandbox is here

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-12
@storm184

You make one more calculated property, by analogy with sum - an array of titles of marked elements:

selectedServices() {
  return this.services.reduce((acc, n) => (n.checked && acc.push(n.title), acc), []);
},

Well, bring it out:
<ul>
  <li v-for="n in selectedServices">{{ n }}</li>
</ul>

UPD. In general, it makes sense to rewrite everything a little so as not to bypass the services array completely twice (or three times, four times - who knows what else will need to be done with the selected elements in the future). Let's make selectedServices an array not of titles, but of the selected elements themselves:
selectedServices() {
  return this.services.filter(n => n.checked);
},

Rendering titles, respectively, will look like this:
<ul>
  <li v-for="n in selectedServices">{{ n.title }}</li>
</ul>

And we use selectedServices to calculate the sum, here we don’t need to touch the checked property anymore:
sum() {
  return this.selectedServices.reduce((acc, n) => acc + n.cost, 0);
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question