登录、注册、注销后跳转
使用this.$router.push({path: 'xxx'})
跳转到指定页面
onLogout(){
auth.logout().then(() => this.$router.push({path: '/login'}))
}
onLogin() {
auth.login({username: this.login.username, password: this.login.password})
.then(() => {
this.login.isError = false
this.login.notice = ''
this.$router.push({path: '/notebooks'})
console.log('start redirect...')
})
.catch(data => {
this.login.isError = true
this.login.notice = data.msg
})
}
登录后获取用户信息
<script lang="ts">
import Vue from 'vue'
import { Component } from 'vue-property-decorator';
import Auth from '@/apis/auth'
@Component
export default class Avatar extends Vue{
username = 'Valley'
created(){
Auth.get_info().then((res: any) => {
if(res.isLogin) {
this.username = res.data.username
}
})
}
get slug() {
return this.username.charAt(0)
}
}
</script>
- slug使用计算属性
- 获取数据写在created声明周期中
css使用text-transform设置大小写
text-transform: uppercase;
组件间事件传递
在helpers目录中新建bus.ts,新建一个vue实例
import Vue from 'vue'
export default new Vue()
在Login组件中触发事件
auth.login({username: this.login.username, password: this.login.password})
.then(() => {
this.login.isError = false
this.login.notice = ''
this.$router.push({path: '/notebooks'})
// 触发事件
Bus.$emit('login', {username: this.login.username})
console.log('start redirect...')
})
在Avatar组件中监听事件
created(){
// 监听事件
Bus.$on('login', data => this.username = data.username)
Auth.get_info().then((res: any) => {
if(res.isLogin) {
this.username = res.data.username
}
})
}
未登录跳转到登录页面
created() {
Auth.get_info().then(res => {
if (!res.isLogin) {
this.$router.push('/login')
}
}
)
}
每个组件的this.$router都指向router
import router from '@/router';
@Component
export default class Avatar extends Vue{
created(){
console.log(this.$router === router) // 结果为true
}}
路由重构
路由改用query传参
router修改
// ...
{
path: '/note',
component: NoteDetail,
},
{
path: '/trash',
component: TrashDetail,
},
// ...
router-link传参
<router-link :to="`/note?notebookId=${notebook.id}`" class="notebook" >
使用$route.query
获取参数
<div id="note-detail">
<h1>notebookId: {{$route.query.notebookId}}</h1>
<h1>noteId: {{$route.query.noteId}}</h1>
</div>
回车登录
实现敲击回车时登录
在输入密码处的input监听回车事件@keyup.enter
,触发登录
<div :class="{show: isShowLogin}" class="login">
<input type="text"
v-model="login.username"
placeholder="输入用户名">
<input type="password"
v-model="login.password"
placeholder="密码"
@keyup.enter="onLogin">
<p v-bind:class="{error: login.isError}">{{login.notice}}</p>
<div class="button"
@click="onLogin">登录</div>
</div>
如果不是在根组件上监听,需要使用.native
修饰符