skip to Main Content

I wanted to read the data from the database and display it in the app.

I’m calling it like this :

 <h2 class="lowongan1" v-for="value in list_lowongan"> {{ value.title }}</h2>
 <p class="descJob1" v-for="value in list_lowongan">{{ value.body }}</p>

The script

export default {
  data() {
    return {
      'form': {
        title: '',
        body: '',
      },

      list_lowongan: []
    };
  },

    mounted() {
        console.log('on mounted');
        axios.get('post/list').then((response) => {
            console.log(response.data)
            this.list_lowongan = response.data
        }).catch((error) => {
            console.log(error)
        });
    },

The problem is, when I call it like that, It displays all the title in the database and the body in the database tables.

How can I make it so that it only display 1 title for each h2 class ?

3

Answers


  1. Use a wrapping div to hold your content and then loop over the div like so:

    <div v-for="value in list_lowongan">
      <h2 class="lowongan1"> {{ value.title }}</h2>
      <p class="descJob1">{{ value.body }}</p>
    </div>
    
    Login or Signup to reply.
  2. You have two for-loops independent of each other so they’ll stack by themselves

    You just need one for-loop to display a list of where each title and body are together

    You can form it this way:

    <div v-for="value in list_lowongan">
        <h2>{{ value.title }}</h2>
        <p>{{ value.body }}</p>
    </div>
    
    Login or Signup to reply.
  3. As per your requirement, No need to use multiple v-for loops for same data iteration. Instead you can achieve that by applying v-for in a wrapper element and then prints the object values inside that wrapper element.

    Live Demo :

    new Vue({
      el: '#app',
      data: {
        list_lowongan: []
      },
      mounted() {
        this.list_lowongan = [{
            title: 'Title 1',
          body: 'Body 1'
        }, {
            title: 'Title 2',
          body: 'Body 2'
        }, {
            title: 'Title 3',
          body: 'Body 3'
        }]
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="(value, index) in list_lowongan" :key="index">
        <h2>{{ value.title }}</h2>
        <p>{{ value.body }}</p>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search