第一步,安裝依賴
npm install vuex
第二步,在根目錄下創建store/store.js或者src文件夾下創建store/index.js(如果在src文件夾下創建store/store.js會報錯),至於為什么要創建,因為我也cil創建的項目,沒有這個文件QAQ
第三步,往store.js中加入代碼
import vue from 'vue'
import vuex from 'vuex'
vue.use(vuex);
//注意大小寫哦
export default new vuex.Store({
state: {
loginSign:false;//這個是定義登錄成功的標准
},
mutations: {//按照規定,修改store.state中數據的唯一方法,當然,你直接暴力也是可以的,暴力方法在后續界面中描述
setLoginSign(state,data){
state.loginSign = data;
}
},
getters: {//類似vue.js的計算屬性
getLoginSign: state => state.loginSign
},
actions:{//提交mutations
setLoginSign(context,data){
context.commit('setLoginSign',data)
}
}
});
第四步,在main.js中導入store文件
import store from '/store/store'
new Vue({
render: h => h(App),
router,
store,//就這
}).$mount('#app');
好吧,我忘記寫路由配置了
第五步,配置路由,在src下直接創建router.js文件
import Vue from 'vue'
import Router from 'vue-router'
import store from '/store/store'//我不想配置全局守衛,我要弄獨享守衛
import Test1 from "./vuestudy/Test1.vue"//你想要跳轉的界面1
import TestVue2 from "./vuestudy/test-2/TestVue2.vue";//界面2
import TestVue1 from "./vuestudy/test-1/TestVue1.vue";//界面3
Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
};
export default new Router({
routes: [
{
path: '/',//默認第一個界面
component: Test1,
meta: {
requireAuth: true
},
//配置獨享守衛
//守衛的調用順序:全局守衛而后才是獨享守衛,=>獨享守衛並不會被覆蓋
beforeEnter: (to, from, next) => {
next();
},
children:[
{
path: '/test-1',
name: 'test-1',
component: TestVue1,
},
{
path: '/test-2',
name: 'test-2',
component: TestVue2,
beforeEnter: (to, from, next) => {
if (from.path === '/test-1'){//比如我設置了要是通過path為'/test-1'進入,則需要驗證是否登錄成功
if(store.state.loginSign){//我們在store中設置了初始值是false
next();
}else{
next(from);//讓他回去
}
}else {
next();
}
},
}
]
},
],scrollBehavior(to, from, savedPosition) {
if (savedPosition && to.meta.keepAlive) {
return savedPosition;
}
return { x: 0, y: 0 };
}
})
第六步,寫登錄界面
export default {
name: "TestVue1",
data(){
return{
account:'',
password:'',
}
},
methods:{
login(){
if (this.account === 'Solitary Orchid' && this.password === '123456'){//懶的寫后端,直接使用數據驗證,其實差別不大,axios返回驗證成功
//this.$store.dispatch('setLoginSign',true);//這一步是通過action來借用mutations修改state中的值,此處也可以是this.$store.commit('setLoginSign',true)
this.$store.state.loginSign = true;//暴力,直接修改state的值
this.$router.push({path:'test-2'})//路由跳轉
}
}
}
}
第一次寫,感覺有點垮,畢竟我也是記錄一下自己學的過程,可能在實際操作過程,你們還會遇見:控制台報錯,cannot read property '$store' of undefine,這個我也遇見過,但是我是因為沒有在router.js中導入store.js文件就直接使用this.$store