What is the process for importing a JavaScript file into a Vue component?

Having trouble importing JSON results into a Vue component?

The results are as follows:

[{"id":"d023c5e3-ca3c-4d97-933a-1112a8516eee",
"score":9001,
"updated":"2018-12-07T13:48:33.6366278",
"player":Johanna,
"category":Funny},
{"id":"398b65fb-e741-4801-be49-926b111ec871",
"score":99,
"updated":"2018-12-11T11:13:42.8312936",
"player":Johanna,
"category":Music}]

Code in GetResult.js:

import axios from 'axios'
const url = 'http://localhost:5000/api/Results';

export default {
  data () {
    return {
      results: {}
    }
  },
  created () {
    axios.get(url)
     .then(response => {
     console.log(response.data)
     this.$data.results = response.data
   })
  .catch(err => {
    console.log(err)
  })
}
}

Code in Toplist.vue:

<template>
  <div class="TopList">
   <table class="table table-striped">
    <thead>
      <tr>
      <th>Name</th>
      <th>Score</th>
      <th>Category</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="result in resultList" :key="result.id">
      <td>{{ result.player }}</td>
      <td>{{ result.score }}</td>
      <td>{{ result.category }}</td>
    </tr>
  </tbody>
</table>
</div>

<script>
import results from './ResultApi/GetResult.js'

export default {
  name: 'TopList', 
  data() {
    return {
     resultList: results
   }
 }
}
</script>

Answer №1

Toplist.vue

// Omitting the HTML portion

<script>
export default {
  name: 'TopList', 
  data() {
    return {
      results: []
    }
  },
  mounted () {
    this.fetchResults()
  },
  methods: { 
    fetchResults () {
      axios.get(url)
        .then(response => this.results = response.data)
        .catch(err => console.error(err))
    }
  }
}
</script>

Here is an example solution tailored for your scenario.

Answer №2

...
created () {
  axios.get(url).then(response => {
    console.log(response.data)
    this.$data.results = response.data // incorrect
    this.results = response.data // correct
  })
...

If you are not using Vuex, move the external code from fetching results into the component itself:

<template>
  <div class="TopList">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Score</th>
          <th>Category</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="{ id, player, score, category } in results" :key="id">
          <td>{{ player }}</td>
          <td>{{ score }}</td>
          <td>{{ category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'TopList',

  data() {
    return {
      url: 'http://localhost:5000/api/Results',
      results: []
    }
  },

  created () {
    axios.get(this.url).then(({ data }) => {
      this.results = data
    }).catch(err => {
      console.log(err)
    })
  }
}
</script>

External file usage:

getResults.js

import axios from 'axios'
const url = 'http://localhost:5000/api/Results'

export default function () {
  axios.get(url)
}

TopList.vue

<template>
  <div class="TopList">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Score</th>
          <th>Category</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="{ id, player, score, category } in results" :key="id">
          <td>{{ player }}</td>
          <td>{{ score }}</td>
          <td>{{ category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import getResults from './ResultApi/getResult.js'

export default {
  name: 'TopList',

  data() {
    return {
      results: []
    }
  },

  created () {
    getResults().then(({ data }) => {
      this.results = data
    }).catch(err => {
      console.log(err)
    })
  }
}
</script>

Modified version of TopList.vue with async function:

<template>
  <div class="TopList">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Score</th>
          <th>Category</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="{ id, player, score, category } in results" :key="id">
          <td>{{ player }}</td>
          <td>{{ score }}</td>
          <td>{{ category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import getResults from './ResultApi/getResult.js'

export default {
  name: 'TopList',

  data() {
    return {
      results: []
    }
  },

  async created () {
    try {
      let { data } = await getResults()
      this.results = data
    } catch(err) {
      console.log(err)
    }
  }
}
</script>

Answer №3

Make sure to receive props from the parent component Check out the documentation here

Let's take a look at this example:

Here is an example of a parent component:

<template>
  <div id="app"><Toplist :result-list="results" /></div>
</template>

<script>
import Toplist from "./components/Toplist.vue";

export default {
  name: "App",
  data() {
    return {
      results: []
    };
  },
  components: {
    Toplist
  },
  mounted() {
    const fetchedData = [
      {
        id: "d023c5e3-ca3c-4d97-933a-1112a8516eee",
        score: 9001,
        updated: "2018-12-07T13:48:33.6366278",
        player: "Johanna",
        category: "Funny"
      },
      {
        id: "398b65fb-e741-4801-be49-926b111ec871",
        score: 99,
        updated: "2018-12-11T11:13:42.8312936",
        player: "Johanna",
        category: "Music"
      }
    ];

    this.results = fetchedData;
  }
};

And here is the child component that receives data from props:

<template>
  <div class="TopList">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Score</th>
          <th>Category</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="result in resultList" :key="result.id">
          <td>{{ result.player }}</td>
          <td>{{ result.score }}</td>
          <td>{{ result.category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "Toplist",
  props: ["resultList"],
  
};
</script>

View the demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does the data in a Vuex store always stay in memory?

Firstly, I want to thank you for your patience with my limited English skills. I am curious if the data in Vuex's store always stays in memory. Let me provide an example. If we receive a list from the server and store it in the Vuex state when enteri ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

Can you explain the extent to which JavaScript's setTimeout() and clearTimeout() apply?

Approximately 30 seconds after a page is loaded or reloaded, a pop-up will be displayed under certain conditions. The following code successfully achieves this functionality: jQuery(document).ready(function($) { .......... if (localStorage.getItem ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

Adding data from one object to another in Javascript results in duplicated entries

Despite my efforts to find a solution for my issue, I couldn't locate a relevant topic. Being new to Javascript, I suspect my lack of understanding is hindering me from resolving the problem. After days of trying, I'm still unable to grasp it. An ...

What could be causing the child of an ES6 imported object to return as undefined?

Here is the code snippet I am working with: import * as _routes from '../../routes' console.log('parent:', _routes) console.log('child:', _routes.breadcrumb) This code produces the following output: https://i.stack.imgur.co ...

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

How to efficiently create a unique object on MongoDB during the first instance

In the project I'm working on, there is a feature where a user can create a safe by visiting /mysafe. However, I want this safe to be created only once when they first visit the page. Subsequent visits should redirect them to /mysafe/theidofit. Have ...

Establishing the initial value for an input file form

Similar Question: Dynamically set value of a file input I'm currently working with an HTML form that includes a file input field, and I'm attempting to set the initial value for the file path in the form. I've tried changing the "value" ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Converting an object to JSON without prior knowledge of its type

Currently, I have a small program that consists of two classes. One class serves as the entry point of my application and deals with commandline arguments upon startup, while the other class contains options that I need to serialize into JSON format for la ...

Connect multiple tables in JSON format

I'm encountering an issue while trying to display data from a JSON file. When I attempt to show the data in a single table, everything works fine. However, if I try to join multiple tables, no data is displayed. <?php mysql_connect($hostname,$user ...

Issue with VueJS beforeRouteEnter hook not triggering

I have been following the steps outlined on this page: https://github.com/vuejs/vue-class-component#adding-custom-hooks Although no errors are appearing, the beforeRouteEnter hook is not triggering. I am not getting any of the expected console output. In ...

Vue.js HTML5 Editor_vueful

I am currently utilizing browserify and attempting to incorporate the vue-html5-editor library from https://github.com/PeakTai/vue-html5-editor. However, when I attempt the following code: Vue.use(require('vue-html5-editor')); An error is thro ...

The use of HTML5 required attribute is ineffective when submitting forms via AJAX

Seeking advice on implementing basic validation for a newsletter form that only requires an email address. The current page layout doesn't allow space for jQuery error messages, so I attempted to use the HTML 5 required attribute. However, the form st ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

The struggle of encoding: Making a JSON ajax call (utf-8) to convert Latin1 characters to uppercase

I've encountered a particular issue: the Javascript library I am developing utilizes JSON cross-domain requests to fetch data from a backend powered by Ruby on Rails: function getData() { $.ajaxSetup({ 'beforeSend': function(xhr) {xhr.s ...