需求:用户通过url访问时,未登录会跳转到204页面,需要在204页面加一个登录的按钮,登陆后,再跳转到原url地址。
//axios.js
export default function ({ $axios , store, app: { router }, redirect}) {
$axios.onResponse(res => {
if (res.status === 204) { //当状态码是204时,判断有没有登录
if(!store.getters.userInfo){
store.commit('setUrl', router.currentRoute.fullPath)//如果没有登录,将url通过mutations存起来
redirect(`/204?path=${router.currentRoute.fullPath}`)//跳转到204页面带上url地址
}else{
redirect('/204')
}
}
})
}
其中,第一个参数是state,后面的参数是向 store.commit 传入的额外的参数,即 mutation 的 载荷(payload)。
store.commit方法的第一个参数是要发起的mutation类型名称,后面的参数均当做额外数据传入mutation定义的方法中。
//store
export const mutations = {
setUrl (state, fullPath204) {
state.fullPath204 = fullPath204//将fullPath204存到
},
}
export const getters = {
// 是否有fullPath204
isFullPath204 (state) {
return state.isFullPath204
},
}
登录时,将path拼接在url后面
export const loginFilter = (type,path) => {
let _type = type
let _curHref = window.location.href
let _mode = process.env.PATH_TYPE
let _domain = _mode === 'production' ? 'www.modb.pro' : 'dev.modb.pro'
let https= _mode === 'production' ? 'https' : 'http'
let _domains = _mode === 'production' ? 'wiki.modb.pro' : 'dev.modb.pro:3001'
if(path){
_curHref = `${https}://${_domains}` + path
}
if(_curHref.includes('login')){
_curHref = `${https}://${_domains}`
}
if(_type){
window.location.href = `https://${_domain}/${_type}?redirect=${_curHref}&site=nimbus`
}else{
window.location.href = `${https}://${_domains}/login`
}
}
//login.vue
<template>
<div class="vertical-horizontal">
<div class="other-way-box">
<div class="item">
<span @click="loginFilter('login',path)">墨天轮账号登录</span>
</div>
</div>
</div>
</template>
<script>
import { loginFilter } from '@/utils'
import { mapActions,mapGetters } from 'vuex'
export default {
name: 'login',
head: {
title: '登录'
},
data () {
return {
fromRoute: '',
path:''
}
},
computed: {
...mapGetters(['isFullPath204']),
},
methods: {
loginFilter (type,path) {
loginFilter(type,path)
},
},
mounted () {
if(this.isFullPath204){
this.path = this.isFullPath204 //登录时判断Vuex中是否有url
}else{
this.path = this.$route.query.redirect
}
}
</script>
以上就是Vuex的使用场景,如果屏幕前的你还没有用过Vuex,可以看看下方的基本使用步骤吖。
Vuex的基本使用
1、安装vuex依赖包
npm install vuex --save
2、导入vuex包 import Vuex from ‘vuex’
Vue.use(Vuex)
3、创建store对象
const store = new Vuex.Store ({
// state 中存放的就是全局共享的数据
state: { count: 0 } })
4、 将store对象挂载到vue实例中
new Vue ({
el: ‘#app’ ,
render:h => h(app),
router,
// 将创建的共享对象,挂载到Vue实例中
// 所有的组件,就可以直接从store中获取全局的数据了
store })
使用Vuex管理数据的好处:
1、能够在vuex中集中管理共享的数据,易于开发和后期维护;
2、能够高效地实现组件之间的数据共享,提高开发效率;
3、存储在vuex的数据都是响应式的,能够实时保持数据与页面的同步;