user13576861
user13576861

Reputation:

Wrapping elements with Vue

Sorry for the long post. In my vue code, I fetch cities from an API.

new Vue({
  data: {
    cities: []
  },
  el: '#app',
  methods: {
    fetchCities() {
      fetch('https://fakeapi.app/cities/')
        .then(response => response.json())
        .then(result => {
          this.cities = result
          console.log(result)

        })
    }
  }
})

... Using this HTML code:

<div id="app">
      <dl>
        <dt>
          <li v-for="city in cities">{{ city.name }}</li>
        </dt>
        <dd>
          <li v-for="city in cities">{{ city.population }}</li>
        </dd>
    </dl>
      <input @click="fetchCities" type="button" value="Get cities">
    </div>

Which produces:

Stockholm
Göteborg
Malmö
Uppsala
Västerås
Örebro
Linköping
Helsingborg
Jönköping
Norrköping
   • 1372565
   • 549839
   • 280415
   • 140454
   • 110877
   • 107038
   • 104232
   • 97122
   • 89396
   • 87247

To be overly-specific: The first row are the cities, and the row under are their respective population.

I want to make so each city name name is in it's own dt-element, and the population is also in it's on dd-element. I also want to use the v-for in combination with atemplete-element so that a dt and a dd-element is created for each city, as the dt-and the dd elements are direct children of the dl-element in the HTML-structure.

I want the outcome to look something like this:

Stockholm
• 1372565
Göteborg
• 549839
Malmö
• 280415
Uppsala
• 140454
Västerås
• 110877
Örebro
• 107038
Linköping
• 104232
Helsingborg
• 97122
Jönköping
• 89396
Norrköping
• 87247

Upvotes: 0

Views: 72

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

  • No need to use <li>, that's only for <ol> and <ul>
  • Iterate using a <template> to get through the cities.
<div id="app">
  <dl>
    <template v-for="city in cities">
      <dt :key="city.name">{{ city.name }}</dt>
      <dd :key="`${city.name}-pop`">{{ city.population}}</dd>
    </template>
  </dl>
  <input @click="fetchCities" type="button" value="Get cities">
</div>

Upvotes: 1

Related Questions