配置一个vue3.0项目的完整步骤

2020-06-16 06:11:25易采站长站整理

代码如下:


import Vue from 'vue'
import Vuex from 'vuex'
// 引入js-cookie
import Cookies from 'js-cookie'
Vue.use(Vuex)

const store = new Vuex.Store({
state: {
name: ''
},
mutations: {
loginIn(state, name) {
state.name = name
// 设置过期时间为1天
Cookies.set('name', name, {
expires: 1
})
},
loginOut(state) {
state.name = ''
Cookies.remove('name')
}
}
})
export default store

我们定义了一个loginIn方法,调用这个方法,我们就可以把用户的用户名存在store中,同时也存在cookie里,cookie的有效期是1天。

配置

修改main.js,把store引入进去main.js中,然后在

new Vue
函数中配置


import store from './store/index.js'
……
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')

好啦,这时候我们就可以愉快的使用store了。

修改

Login.vue
onSubmit
方法,用户登录成功后,就把用户信息存在store中。


if (res.data.status === 1) {
// 将用户信息存储在vuex中
this.$store.commit('loginIn', this.form.name)
// 如果登录成功则跳转我index页面
this.$router.push('/index')
} else {
……
}

修改

Index.vue
页面,我们就可以在这个页面获取登录用户的用户名了。

Index.vue
代码如下:


<template>
<div>这里是Index 页面,此时登录的用户是{{userName}}</div>
</template>
<style>
</style>
<script>
export default {
name: 'Index',
data() {
return {
}
},
computed: {
userName() {
return this.$store.state.name
}
},
}
</script>

自此,一个我们常用vue项目基本上配置完成了。当然不同的项目,还有不同的组件需要安装,到时候你们再根据情况确定吧。

最后再讲一个关于路由拦截的问题。

15.路由拦截

现在我们的项目已经有登录功能了,但是并没有对用户进行限制。比如我的Index.vue页面要求只有登录用户才能访问。这时该怎么办呢? 这就要用路由拦截了,凡是没有登录的用户要访问Index.vue的时候,统一让他重定向到Login页面,让其登录。

修改main.js。添加如下代码:


// 设置路由拦截