【问题标题】:How to click on a user & show the user details in another component/view with Vuejs router?如何使用 Vuejs 路由器单击用户并在另一个组件/视图中显示用户详细信息?
【发布时间】:2019-04-18 04:16:18
【问题描述】:

我正在使用 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>

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


任何帮助将不胜感激!

【问题讨论】:

    标签: javascript vue.js vuejs2 axios vue-router


    【解决方案1】:

    您可以使用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))
    }
    

    【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2021-05-01
    • 2020-05-01
    相关资源
    最近更新 更多