在vue3中怎么把登陆页面的用户名通过props传到登陆后的页面上,而且登陆页面是单独一页
时间: 2023-11-17 10:04:20 浏览: 20
在Vue 3中,可以使用路由传参的方式将登陆页面的用户名传递给登陆后的页面。
1. 在路由配置文件中,定义需要传递的参数:
```javascript
const routes = [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/home/:username', // 定义参数名为username
name: 'Home',
component: Home
}
];
```
2. 在登陆成功后,使用`this.$router.push()`方法跳转到Home页面,并将用户名作为参数传递:
```javascript
// 登陆成功后跳转到Home页面
this.$router.push({
name: 'Home',
params: { username: this.username } // 将用户名作为参数传递
});
```
3. 在Home页面中,使用`this.$route.params`获取传递的参数:
```javascript
export default {
name: 'Home',
computed: {
username() {
return this.$route.params.username; // 获取传递的用户名参数
}
}
};
```
4. 在组件中通过props将参数传递给子组件:
```javascript
<template>
<div>
<h1>Welcome, {{ username }}</h1>
<ChildComponent :username="username"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent';
export default {
name: 'Home',
components: {
ChildComponent
},
computed: {
username() {
return this.$route.params.username;
}
}
};
</script>
```
5. 在子组件中接收props参数:
```javascript
<template>
<div>
<h2>Hello, {{ username }}</h2>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: ['username']
};
</script>
```