Please review my code.
<template>
<div class="row flex">
<div class="col-md-6 home_feed">
<post-detail :posts="posts"></post-detail>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
async asyncData (params) {
let { data } = await axios.get('http://localhost:8000/api/v1/users/' + this.$route.params.id + '/')
return {
posts: data
}
},
components: {
'post-detail': Item
}
}
</script>
I got this error: Cannot read property '$route' of undefined when I asyncdata from params.id, but when I type: console.log(this.$route.params.id), it goes right. How can I fix this
if you want to load data from server (from browser) in mounted lifecycle try this:
export default {
data() {
return {
data: {}
}
},
mounted() {
this.asyncData();
},
methods: {
async asyncData ({ route }) {
let { data} = await axios.get('http://localhost:8000/api/v1/users/' + this.$route.params.id + '/')
this.data = data
}
}
}
Response from server will be available in response variable.
For SSR you can do :
async asyncData ({ store, route }) {
let { data} = await axios.get('localhost:8000/api/v1/users/'; + route.params.id + '/')
return {
posts: data
}
}
asyncData will be called before the components are instantiated, and it doesn't have access to this. (see https://ssr.vuejs.org/en/data.html Logic Collocation with Components for details)
For SSR you can change
<script>
async asyncData ({ store, route }) {
let { data} = await axios.get('localhost:8000/api/v1/users/' + this.$route.params.id + '/')
return {
posts: data
}
}
</script>
to
<script>
async asyncData ({ route }) {
let { data} = await axios.get('localhost:8000/api/v1/users/' + route.params.id + '/')
return {
posts: data
}
}
</script>
According to the nuxt tutorial you can not have access to this inside asyncData because it is called before initiating the component. Nuxt Documentation
#Mikhail
This code is success:
export default {
data() {
return {
data: {}
}
},
mounted() {
this.asyncData();
},
methods: {
async asyncData ({ route }) {
let { data} = await axios.get('http://localhost:8000/api/v1/users/' + route.params.id + '/')
this.data = data
}
}
}
But when get API parent-children data like this: {{data.user.username}}, data.user goes undefined. So API data goes error.
I use Nuxt and your code for SSR not work:
Error: Cannot read property $route of undefined
<script>
async asyncData ({ store, route }) {
let { data} = await axios.get('localhost:8000/api/v1/users/'; + this.$route.params.id + '/')
return {
posts: data
}
}
</script>
Related
I am trying to migrate a small project from Nuxt2 to Nuxt3. in Nuxt2, I used axios for making API calls.
now i want to fetch in nuxt3 but Axios doesn't work here.
how to migrate this code to usefetch method in Nuxt3.
this is what i had in nuxt2
<script>
import axios from "axios";
export default {
data() {
return {
allDestinations: [],
allSubDestinations: [],
allTours: [],
form: "",
};
},
async asyncData({ route }) {
let { data: countrydata } = await axios.get(
`${process.env.backendapi}/dests/getcountry/${route.query.countryid}`
);
let { data: allDest } = await axios.get(
`${process.env.backendapi}/dests/getmaindests?limit=5000`
);
let { data: allSubDest } = await axios.get(
`${process.env.backendapi}/dests/getsubdests?limit=5000`
);
let { data: alltours } = await axios.get(
`${process.env.backendapi}/tours/gettours?limit=10000`
);
return {
form: countrydata,
allDestinations: allDest.results,
allSubDestinations: allSubDest.results,
allTours: alltours.results,
};
},
};
</script>
The equivalent to that in Nuxt3would be the following.
.env
NUXT_PUBLIC_TEST_URL="https://jsonplaceholder.typicode.com"
nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
runtimeConfig: {
public: {
testUrl: '', // fallback empty string, must be present tho
},
},
})
With this in any page
<template>
<section>
<div>{{ todo.title }}</div>
<div>{{ user.email }}</div>
<div>{{ photos }}</div>
</section>
</template>
<script setup>
const { testUrl } = useRuntimeConfig()
const route = useRoute() // let's suppose that `countryid` equals 1
const { data: todo } = await useFetch(`${testUrl}/todos/1`)
const { data: user } = await useFetch(`${testUrl}/users/${route.query.countryid}`)
const { data: photos } = await useFetch(`${testUrl}/photos/`)
</script>
More details regarding data fetching can be found here: https://v3.nuxtjs.org/guide/features/data-fetching
But overall, useFetch is blocking and doing what you expect.
If you cannot use script setup, you need to write it like this: https://v3.nuxtjs.org/guide/features/data-fetching#using-async-setup
Here is the documentation regarding env variables: https://v3.nuxtjs.org/guide/features/runtime-config#environment-variables
In my /projects/_slug.vue I have the line:
<Header :title="project.title" :subtitle="project.subtitle" />
by fetching the object in the same file with:
async asyncData({ $content, params }) {
const project = await $content("projects", params.slug).fetch();
return { project };
}
Now my question: I'd like to move Header out of /projects/_slug.vue to /layouts/default.vue. Is it somehow possible to get project.title and project.subtitle in this file?
Layouts don't have asyncData, but they support the fetch hook. There, you could access the Nuxt context via $nuxt.context, which contains $content() and $route (for params):
<template>
<Header :title="project.title" :subtitle="project.subtitle" />
</template>
<script>
export default {
data() {
return {
project: {}
}
},
async fetch() {
const { $content, route } = this.$nuxt.context;
const { params } = route;
this.project = await $content("hello", params.slug).fetch();
},
}
</script>
I'm using Nuxt.js in static site mode, and trying to get an image from an API using a string passed in a prop, however, in the template I am getting [object Promise]. I would've thought that return before the get request would resolve the promise, but I think my grasp of promises and Nuxt.js a little off. Any help would be greatly appreciated.
<template>
<div>
{{ getThumbnailSrc() }}
</div>
</template>
<script>
import axios from 'axios'
export default {
props: {
link: {
type: String,
required: true
}
},
data() {
return {
imageUrl: null
}
},
methods: {
getVimeoId(link) {
return link.split('/').pop()
},
getThumbnailSrc() {
return axios
.get(
`https://vimeo.com/api/v2/video/${this.getVimeoId(
this.link
)}.json`
)
.then(response => {
const vimeoThumbnailUrl = response.data[0].thumbnail_large
console.log(vimeoThumbnailUrl)
return {
vimeoThumbnailUrl
}
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
It sure won't! XHR requests are asynchronous and therefore the template has no idea that it needs to wait.
Solve it by using an additional data property on the component, and using that instead:
data() {
return {
imageUrl: null,
thumbnailSrc: null
}
},
And in your callback:
.then(response => {
const vimeoThumbnailUrl = response.data[0].thumbnail_large
console.log(vimeoThumbnailUrl)
this.thumbnailSrc = vimeoThumbnailUrl
})
Now you can use {{thumbnailSrc}} and it will load appropriately.
I am trying to do a GET request using Axios , but get the following error in console:
TypeError: Cannot set property 'films' of undefined
at eval (SearchBar.vue?e266:26)
SearchBar.vue
<template>
<section>
<input v-model='film' type='text' list='films'>
<datalist id='films'>
<option v-for='film in films' :key='film.episode_id'>{{film}}</option>
</datalist>
</section>
</template>
<script>
import axios from "axios";
export default {
name: "SearchBar",
data() {
return {
film: "",
films: []
};
},
created() {
axios
.get("https://swapi.co/api/films/")
.then(function(response) {
// handle success
//console.log(response);
this.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
};
</script>
Anyone can tell me why I get the error? Note: I am running this locally for instant prototyping via Vue-Cli
One way is to use Arrow function:
created() {
axios
.get("https://swapi.co/api/films/")
.then((response) => {
// handle success
//console.log(response);
this.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
2. Another way that = this & then use that inside promise callback
created() {
const that = this; // <-- assign this in that
axios
.get("https://swapi.co/api/films/")
.then(function (response) {
// handle success
//console.log(response);
that.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
I get a issues with Axios Get with Header in Vuex - VueJS, hope you guys help me.
Pages:
<template>
<div class="temp">{{users.info}}</div>
</template>
<script>
data: function () {
return {
config: {
'headers': {'Authorization': 'JWT ' + this.$store.state.token}
}
}
},
fetch ({ store, params }) {
return store.dispatch('getProfile', params, this.config)
},
</script>
Vuex Modules:
import api from '~/plugins/axios'
const state = () => {
return {
info: null
}
}
const actions = {
getProfile ({commit}, params, config) {
return new Promise((resolve, reject) => {
api.get(`/users/${params.username}/`, config)
.then(response => {
commit('GET_USER_DETAIL', response.data)
resolve(response.data)
},
response => {
reject(response.data)
})
})
}
}
const getters = {}
const mutations = {
GET_USER_DETAIL (state, info) {
state.info = info
}
}
export default {
state,
actions,
getters,
mutations
}
Issues: config in Vuex module is not defined.
I think Im wrong with something hope your help.
Thanks in advance!
Actions in Vuex can't contain more than one parameter. Group up your params into a single object, like so:
return store.dispatch('getProfile', { params: params, config: this.config })
Then access from your action like so:
getProfile ({commit}, obj) {
var params = obj.params
var config = obj.config
/* ... */
}
If you look at the section Dispatching Actions in the docs it shows the correct way to pass params.