如何点击用户并使用Vuejs路由器在另一个组件/视图中显示用户详细信息?

问题描述 投票:0回答:1

我正在与Vuejs做一个项目,我需要以下内容:

  • 使用API​​并在主页中获取用户列表(只是用户名)。
  • 创建自定义搜索过滤器以按名称查找用户。
  • 单击用户名时,我需要重定向到另一个组件并在该组件中输出该用户的详细信息(仅显示我单击的用户的详细信息)。

我完成了前两个任务。但是,我不知道如何做其他第三项任务。我正在阅读vue-router的文档,但我无法弄明白。

我使用axios来获取用户列表和jsonplaceholder

用户列表组件:

<template>
  <div>
    <!-- List Rendering the response data stored in posts[] array -->
    <b-input id="inline-form-input-name" class="my-3 col-10 col-sm-10 col-md-4 col-lg-4" type="text" v-model="searchUsers" placeholder="Search Users..."
    ></b-input>
    <h2>Our users:</h2>
    <div v-for="user in filteredUsers" :key="user.id">
      <p v-b-tooltip.hover.right='"Click on user to know more"' class="users pr-2"><span>{{ user.id }}</span> - {{ user.name }}</p>
    </div>
  </div>
</template>

<script>

// import axios
import axios from 'axios'

export default {
  name: 'UsersList',
  data() {
    return {
      users: [],
      searchUsers: ''
    }
  },
  computed: {
    // custom search box for user names
    filteredUsers() {
      return this.users.filter(user => {
        return user.name.match(this.searchUsers)
      })
    }
  },
  // life cycle hook - calls axios
  created(){
    axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
      console.log(response.data)
      this.users = response.data
      // console.log an error if get() method is unsuccessful
    }).catch(err => {
      console.log(err)
    })
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

.users {
  cursor: pointer;
  display: inline-block;
}
</style>

用户列表组件的名称是UserList.vue

我需要在这个名为UsersDetails.vue的组件中输出用户详细信息

<template>
    <div class="user-details-wrapper">
        <h1>I am the user details component</h1>
    </div>
</template>


<script>
export default {
    name: 'UserDetails',
    data(){
        return {

        }
    },
}
</script>

<style lang="scss">

.user-details-wrapper {
    h1 {
        background: #000;
        color: #fff;
        padding: 10px;
        margin-top: 30px;
        display: inline-block;
    }
}

</style>

截图用户列表和自定义搜索过滤器

enter image description here enter image description here


任何帮助将真正感激它!

javascript vue.js vuejs2 axios vue-router
1个回答
2
投票

你可以使用Dynamic Route Matching

添加路线

const router = new VueRouter({
  routes: [
    // dynamic segments start with a colon
    { path: '/user/:id', component: User }
  ]
})

动态段由冒号:表示当路径匹配时,动态段的值将在每个组件中公开为this.$route.params

Single User component做一个AJAX呼叫安装

mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users/" + this.$route.params)
    .then(res => console.log(res))
}
© www.soinside.com 2019 - 2024. All rights reserved.