store/state.js
export default {
userInfo: ''
}
store/mutations.js
export default {
login (state, v) {
state.userInfo = v
}
}
(一)路由守卫,用户信息为空就跳登录页
main.js
import store from './store'
router.beforeEach((to, from, next) => { // 路由守卫
console.log(store.state, 'store.state')
console.log(to)
// 用户信息为空跳login页
if (store.state.userInfo || to.path === '/login') {
next()
} else {
next({
path: '/login'
})
}
})
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
(二)点击登录,改写state里的数据
login.vue
<template>
<div>
<h1>登录页</h1>
<input type="text"
v-model="username">
<input type="text"
v-model="password">
<button @click="login">登录</button>
</div>
</template>
<script>
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login: function () {
if (this.username && this.password) {
// 改变state里的值 this.$store.commit('mutations方法名',值)
this.$store.commit('login', {
username: this.username,
password: this.password
})
this.$router.push('/') // 跳首页
}
}
}
}
</script>
555

被折叠的 条评论
为什么被折叠?



