[英]Vue.js - switching from one component to another
I'm quite new to vue.js.我对 vue.js 很陌生。 I have a page that lists details of a list of people, with an 'Edit' button against each person.我有一个页面,其中列出了人员列表的详细信息,每个人都有一个“编辑”按钮。 When I click the Edit button, I want to switch to another page which shows a form for editing the selected person's details.当我单击“编辑”按钮时,我想切换到另一个页面,该页面显示用于编辑所选人员详细信息的表单。
I'm not sure what is the best way to do this.我不确定这样做的最佳方法是什么。 I'm using Bootstrap and Router in my solution.我在我的解决方案中使用 Bootstrap 和路由器。
Option 1 : I thought it would be straightforward to route to '/person/:id' when clicking the Edit button, but not sure how to do this from the click handler method.选项 1 :我认为单击“编辑”按钮时路由到“/person/:id”会很简单,但不确定如何通过单击处理程序方法执行此操作。
Option 2 : Below is the main component, where I'm trying to switch between the two components 'PersonsList' and 'EditPersonData' upon receiving an event from either.选项 2 :下面是主要组件,我试图在接收到来自任一组件的事件时在两个组件“PersonsList”和“EditPersonData”之间切换。 PersonsList is emitting the event successfully, but I'm not sure how to listen to it here and switch to EditPesonData component. PersonsList 正在成功发出事件,但我不确定如何在这里收听并切换到 EditPesonData 组件。
Home.vue主页.vue
<template> <div class="home"> <h1 class='home-text'> {{message}} </h1> <component v-bind:is="component"/> </div> </template> <script> import PersonsList from '@/components/PersonsList' import EditPersonData from '@/components/EditPersonData' export default { name: 'Home', data() { return { message: 'Welcome to Person Details,': component, "PersonsList" } }: components, { PersonsList; EditPersonData } }; </script>
Any help would be very much appreciated.任何帮助将不胜感激。
Thanks谢谢
The best way would be to send the id
as a param
in the route /person/:id
.最好的方法是在路由/person/:id
中将id
作为param
发送。 To do this, you can append the id of each list item, for example:为此,您可以 append 获取每个列表项的 id,例如:
<div v-for="(user,index) in userList" :key="index">
<a :href="'/person/' + user.id">Edit</a>
</div>
Then, you would get it in the other component as this.$route.params.id
in order to get more details about the user of this id.然后,您将在其他组件中将其作为this.$route.params.id
获取,以获取有关此 id 用户的更多详细信息。
Make sure you define the route in the router with the id param as follows: person/:id
确保使用 id 参数在路由器中定义路由,如下所示: person/:id
UPDATE:更新:
If you want to change the route on a click
function:如果要更改路线, click
function:
<b-btn @click="editPerson(user.id)">Edit</b-btn>
And in the methods, add the function as follows:在方法中,添加 function 如下:
editPerson(userId){
this.$router.push({
name: 'person',
params: { id: userId }
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.