Home > Enterprise >  loop json data and append in document nuxtjs code
loop json data and append in document nuxtjs code

Time:03-14

After clicking on the button it requests json data and creates the elements inside (div)

The problem here is when I add nuxt code, for example "Components" it doesn't process it adding it as it is

enter image description here

axios.get('/user.json').then(function(status) {
    $('.creator-content .row').append(`
                <div >
            <div >
              <div >
                <img src="@/assets/image/background-user.svg" loading="lazy" />
              </div>
              <div >
                <nuxt-link to="/"><h4>${status.title}</h4></nuxt-link>
                <nuxt-link to="/" >${status.class}</nuxt-link>

                <p >@desr</p>
                <div >
                  <nuxt-link to="/"
                    ><img src="@/assets/image/icon.svg" /><span
                      >${status.content}<</span
                    ></nuxt-link
                  >
                </div>
              </div>
              <orBtn textBtn="follow" to="/" icon="ri-user-add-line" />
            </div>
          </div>
      `);
});

CodePudding user response:

As mentioned in the docs, this is how you would fetch and populate a state in a Nuxt context:

<template>
  <div>
    <p v-if="$fetchState.pending">Fetching mountains...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt Mountains</h1>
      <ul>
        <li v-for="mountain of mountains">{{ mountain.title }}</li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        mountains: []
      }
    },
    async fetch() {
      this.mountains = await fetch(
        'https://api.nuxtjs.dev/mountains'
      ).then(res => res.json())
    }
  }
</script>

Further knowledge regarding reactive lists can be found on the Vue documentation: https://vuejs.org/guide/essentials/list.html

CodePudding user response:

If the object you are fetching is always the same, you can show the HTML by setting v-if in a component and passing the desired props to it.

<template>
  <ComponentWithProps
    v-if="showData"
    :title="status.title"
    :
    :content="status.content"
  />
</template>

<script>
  export default {
    // Import your component here ...
    data() {
      return {
        status: null
        showData: false
      }
    },
    async fetch() {
      axios.get('/user.json')
        .then((status) => {
          this.status = status;
          this.showData = true;
        }
        .catch(() => {
          this.status = null;
          this.showData = false;
        })
    }
  }
</script>
  • Related