通过
state.userInfo
控制用户登录路由权限
文章标题
一、 效果展示
二、 代码展示
1-0 router.js
import Vue from "vue"
import VueRouter from "vue-router"
Vue.use(VueRouter)
const router = new VueRouter({
mode: "history",
base: "/",
routes: [
{
path: "/login",
name: "login",
component: () => import("./pages/login.vue")
},
{
path: "/",
name: "index",
component: () => import("./pages/index.vue")
}
]
})
export default router
1-1 store文件夹下
1-1-1 state.js
state ---- 数据仓库
- state是比较强大的json,用来存储数据
export default {
userInfo: "",
}
1-1-2 index.js
import Vue from "vue"
import Vuex from "vuex"
import state from "./state"
import mutations from "./mutations"
import getters from "./getters"
import actions from "./actions"
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
1-1-3 mutation.js
mutation ---- 用来修改数据的
- 为什么不能直接实例化state,然后直接修改state的数据
- 通过commit一个mutation,然后通过mutation传入state再对state进行修改
- 同步的
- 就是一个function
export default {
login(state, v) {
state.userTnfo = v
}
}
1-2 main.js
1.引入store
import store from "./store";
2. 控制未登录之前不能访问其他页面
router.beforeEach((to,from, next) => {
if(store.state.userInfo || to.path === "/login"){
next()
} else {
next({
path: "/login"
})
}
)
1-3 pages下的login.vue
<template>
<div class="login">
<p class="login-title">
登陆权限
</p>
<div class="section">
<input
class="section-input"
v-model="form.account"
placeholder-class="input-holder"
placeholder="请输入您的账号"
/>
</div>
<div class="section">
<input
class="section-input"
type="password"
v-model="form.password"
placeholder-class="input-holder"
placeholder="请输入您的密码"
/>
</div>
<button class="btn" @click="login">登录</button>
</div>
</template>
<script>
import store from "../store";
export default {
data() {
return {
isHidden: false,
isPassword: true,
logs: [],
form: {
account: "",
password: ""
}
};
},
created() {},
mounted() {},
methods: {
login() {
if (!this.form.account || !this.form.password) {
alert("请填写账号密码");
return false;
}
const that = this;
setTimeout(() => {
store.commit("login", {
account: that.form.account,
password: that.form.password
});
that.$router.push("./");
}, 500);
}
}
};
</script>
<style lang="less">
.login {
position: relative;
top: 0;
left: 0;
padding: 0 45px;
p {
text-align: center;
}
&-title {
color: #111111;
font-size: 36px;
padding: 40px 0 30px;
}
.section {
&-input {
width: 100%;
height: auto;
border: none;
margin-bottom: 30px;
outline: none;
font-size: 16px;
line-height: 1.6;
border-bottom: 1px solid red;
}
.input-holder {
color: #777777;
font-size: 16px;
}
}
.btn {
width: 100%;
height: auto;
color: #fff;
background: #373737;
margin: 10px 0 20px;
padding: 15px;
box-sizing: border-box;
border-radius: 5px;
font-size: 16px;
}
.btn-primary {
color: #373737;
background: #fff;
}
.login-text {
position: fixed;
left: 0;
bottom: 60px;
width: 100%;
height: auto;
font-size: 12px;
color: #777777;
text-align: center;
}
}
</style>
二、 总结
- 创建store文件夹,进行初始化
- 在 main.js 中创建全局的导航守卫中,拿取到这个实例
- 在login组件中通过
store.commit
提交userInfo数据