I have a list of users retrieved from an API. I want to ensure that when you click on a user's name, it opens a separate page with their information and a unique link.
UsersList Component
<button @click="showUserPage(user.id)">Go to the user's page</button>
data() {
return {
users: []
}
}
showUserPage(userId) {
// Navigate to user details
this.$router.push({ name: 'user-page', params: { userId: userId } })
}
fetchUsers() {
axios.get('https://jsonplaceholder.typicode.com/users/')
.then(response => {
this.users = response.data;
})
.catch(error => {
console.error('Error loading users', error);
});
UserPage Component
data(){
return{
user: {},
}
},
methods:{
getUser(userId) {
axios.get(`https://jsonplaceholder.typicode.com/users?userId=${userId}`)
.then(response => {
this.user = response.data;
})
.catch(error => {
console.error('Error loading users', error);
});
}
created() {
this.getUser(this.$route.params.userId)
router.js
const routes = [
{ path: '/', component: UserList },
{ path: '/user/:userId',name:'user-page', component: UserPage }
]
Upon clicking the button, a link with the correct ID will appear (e.g., 'http://localhost:8080/#/user/8'). However, when attempting to display user information using {{user.name}}
, I encounter an error 'Uncaught ReferenceError: user is not defined'. Additionally, trying to log this.$route.params.userId
results in an error "cannot read properties of null (reading '$route'). What am I missing?