I'm new to Vue.js
and Axios
. I don't quite understand how to get the data
option to work when used within a component.
Why doesnt' my test work?
I get the following error in the console:
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. [Vue warn]: Property or method "symbols" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in root instance)
My simple test:
My data (snipped for brevity):
[{"id":1, "name": "Airfield"}, {"id":2, "name": "Ship Yard"}]
My component:
Vue.component('symbols-table', { template: '<h1>Hello World</h1>', data: { symbols: [] }, created: function(){ axios.get('symbols.json').then(response => this.symbols = response.data); } });
Vue instance:
var app = new Vue({ el: '#app' });
My HTML:
<symbols-table> <ul><li v-for="symbol in symbols">{{symbol.name}}</li></ul> </symbols-table>
First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.
A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() . The get() method requires two parameters to be supplied to it.
Put the fetchData function above in the useEffect hook and call it, like so: useEffect(() => { const url = "https://api.adviceslip.com/advice"; const fetchData = async () => { try { const response = await fetch(url); const json = await response. json(); console. log(json); } catch (error) { console.
As the error is saying:
The "data" option should be a function
In the component, the data must be a function, you need to modify the data block to be a function which will return the data structure to be used in DOM in a reactive way:
Vue.component('symbols-table', { template: '<h1>Hello World</h1>', data: function() { return { symbols: [] } }, created: function(){ axios.get('symbols.json').then(response => this.symbols = response.data); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With