在vue3中怎么把登陆页面的用户名通过props传到登陆后的页面上
时间: 2024-05-11 15:14:04 浏览: 8
在登录页面的组件中,可以通过props把用户名传到父组件中,然后在父组件中使用路由跳转到登录后的页面,同时把用户名作为参数传递。
以下是示例代码:
```html
<!-- 登录页面组件 -->
<template>
<div>
<input v-model="username" type="text" placeholder="请输入用户名">
<button @click="login">登录</button>
</div>
</template>
<script>
export default {
name: 'Login',
data() {
return {
username: '',
}
},
methods: {
login() {
// 登录操作...
// 把用户名通过props传到父组件中
this.$emit('login-success', this.username)
}
}
}
</script>
```
```html
<!-- 父组件 -->
<template>
<router-view :username="username"></router-view>
</template>
<script>
export default {
name: 'App',
data() {
return {
username: '',
}
},
methods: {
onLoginSuccess(username) {
// 登录成功后跳转到登录后的页面,并把用户名作为参数传递
this.$router.push({
name: 'Home',
params: { username }
})
}
},
mounted() {
// 监听登录页面的登录成功事件
this.$on('login-success', this.onLoginSuccess)
},
beforeUnmount() {
// 在组件销毁前解绑事件
this.$off('login-success', this.onLoginSuccess)
}
}
</script>
```
```html
<!-- 登录后的页面组件 -->
<template>
<div>
<h1>欢迎 {{ username }} 登录!</h1>
</div>
</template>
<script>
export default {
name: 'Home',
props: ['username']
}
</script>
```
在登录页面组件中,通过 `$emit` 方法触发 `login-success` 事件,并把用户名作为参数传递,父组件中监听该事件,在事件处理函数中进行路由跳转,并把用户名作为参数传递给登录后的页面组件。在登录后的页面组件中,通过 `props` 接收传递过来的用户名。