vuex add namespaced

This commit is contained in:
Pan 2019-03-20 13:44:42 +08:00
parent 7c33568883
commit 0c50029cf7
20 changed files with 414 additions and 382 deletions

View File

@ -27,7 +27,7 @@ export default {
methods: { methods: {
handleSetLanguage(lang) { handleSetLanguage(lang) {
this.$i18n.locale = lang this.$i18n.locale = lang
this.$store.dispatch('setLanguage', lang) this.$store.dispatch('app/setLanguage', lang)
this.$message({ this.$message({
message: 'Switch Language Success', message: 'Switch Language Success',
type: 'success' type: 'success'

View File

@ -32,7 +32,7 @@ export default {
methods: { methods: {
handleSetSize(size) { handleSetSize(size) {
this.$ELEMENT.size = size this.$ELEMENT.size = size
this.$store.dispatch('setSize', size) this.$store.dispatch('app/setSize', size)
this.refreshView() this.refreshView()
this.$message({ this.$message({
message: 'Switch Size Success', message: 'Switch Size Success',
@ -41,7 +41,7 @@ export default {
}, },
refreshView() { refreshView() {
// In order to make the cached page re-rendered // In order to make the cached page re-rendered
this.$store.dispatch('delAllCachedViews', this.$route) this.$store.dispatch('tagsView/delAllCachedViews', this.$route)
const { fullPath } = this.$route const { fullPath } = this.$route

View File

@ -48,7 +48,7 @@ export default {
}, },
methods: { methods: {
handleClickOutside() { handleClickOutside() {
this.$store.dispatch('closeSideBar', { withoutAnimation: false }) this.$store.dispatch('app/closeSideBar', { withoutAnimation: false })
} }
} }
} }

View File

@ -75,10 +75,10 @@ export default {
}, },
methods: { methods: {
toggleSideBar() { toggleSideBar() {
this.$store.dispatch('toggleSideBar') this.$store.dispatch('app/toggleSideBar')
}, },
async logout() { async logout() {
await this.$store.dispatch('Logout') await this.$store.dispatch('user/logout')
// In order to re-instantiate the vue-router object to avoid bugs // In order to re-instantiate the vue-router object to avoid bugs
location.reload() location.reload()
} }

View File

@ -34,7 +34,7 @@ export default {
return this.$store.state.settings.tagsView return this.$store.state.settings.tagsView
}, },
set(val) { set(val) {
this.$store.dispatch('changeSetting', { this.$store.dispatch('settings/changeSetting', {
key: 'tagsView', key: 'tagsView',
value: val value: val
}) })

View File

@ -106,14 +106,14 @@ export default {
for (const tag of affixTags) { for (const tag of affixTags) {
// Must have tag name // Must have tag name
if (tag.name) { if (tag.name) {
this.$store.dispatch('addVisitedView', tag) this.$store.dispatch('tagsView/addVisitedView', tag)
} }
} }
}, },
addTags() { addTags() {
const { name } = this.$route const { name } = this.$route
if (name) { if (name) {
this.$store.dispatch('addView', this.$route) this.$store.dispatch('tagsView/addView', this.$route)
} }
return false return false
}, },
@ -125,7 +125,7 @@ export default {
this.$refs.scrollPane.moveToTarget(tag) this.$refs.scrollPane.moveToTarget(tag)
// when query is different then update // when query is different then update
if (tag.to.fullPath !== this.$route.fullPath) { if (tag.to.fullPath !== this.$route.fullPath) {
this.$store.dispatch('updateVisitedView', this.$route) this.$store.dispatch('tagsView/updateVisitedView', this.$route)
} }
break break
} }
@ -133,7 +133,7 @@ export default {
}) })
}, },
refreshSelectedTag(view) { refreshSelectedTag(view) {
this.$store.dispatch('delCachedView', view).then(() => { this.$store.dispatch('tagsView/delCachedView', view).then(() => {
const { fullPath } = view const { fullPath } = view
this.$nextTick(() => { this.$nextTick(() => {
this.$router.replace({ this.$router.replace({
@ -143,7 +143,7 @@ export default {
}) })
}, },
closeSelectedTag(view) { closeSelectedTag(view) {
this.$store.dispatch('delView', view).then(({ visitedViews }) => { this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
if (this.isActive(view)) { if (this.isActive(view)) {
this.toLastView(visitedViews) this.toLastView(visitedViews)
} }
@ -151,12 +151,12 @@ export default {
}, },
closeOthersTags() { closeOthersTags() {
this.$router.push(this.selectedTag) this.$router.push(this.selectedTag)
this.$store.dispatch('delOthersViews', this.selectedTag).then(() => { this.$store.dispatch('tagsView/delOthersViews', this.selectedTag).then(() => {
this.moveToCurrentTag() this.moveToCurrentTag()
}) })
}, },
closeAllTags(view) { closeAllTags(view) {
this.$store.dispatch('delAllViews').then(({ visitedViews }) => { this.$store.dispatch('tagsView/delAllViews').then(({ visitedViews }) => {
if (this.affixTags.some(tag => tag.path === view.path)) { if (this.affixTags.some(tag => tag.path === view.path)) {
return return
} }

View File

@ -7,7 +7,7 @@ export default {
watch: { watch: {
$route(route) { $route(route) {
if (this.device === 'mobile' && this.sidebar.opened) { if (this.device === 'mobile' && this.sidebar.opened) {
store.dispatch('closeSideBar', { withoutAnimation: false }) store.dispatch('app/closeSideBar', { withoutAnimation: false })
} }
} }
}, },
@ -17,8 +17,8 @@ export default {
mounted() { mounted() {
const isMobile = this.isMobile() const isMobile = this.isMobile()
if (isMobile) { if (isMobile) {
store.dispatch('toggleDevice', 'mobile') store.dispatch('app/toggleDevice', 'mobile')
store.dispatch('closeSideBar', { withoutAnimation: true }) store.dispatch('app/closeSideBar', { withoutAnimation: true })
} }
}, },
methods: { methods: {
@ -29,10 +29,10 @@ export default {
resizeHandler() { resizeHandler() {
if (!document.hidden) { if (!document.hidden) {
const isMobile = this.isMobile() const isMobile = this.isMobile()
store.dispatch('toggleDevice', isMobile ? 'mobile' : 'desktop') store.dispatch('app/toggleDevice', isMobile ? 'mobile' : 'desktop')
if (isMobile) { if (isMobile) {
store.dispatch('closeSideBar', { withoutAnimation: true }) store.dispatch('app/closeSideBar', { withoutAnimation: true })
} }
} }
} }

View File

@ -29,18 +29,18 @@ router.beforeEach((to, from, next) => {
if (store.getters.roles.length === 0) { if (store.getters.roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息 // 判断当前用户是否已拉取完user_info信息
store store
.dispatch('getInfo') // dispatch @/store/modules/user login getInfo .dispatch('user/getInfo')
.then(res => { .then(res => {
// 拉取user_info // 拉取user_info
const { roles } = res // note: roles must be a object array! such as: [{id: '1', name: 'editor'}, {id: '2', name: 'developer'}] const { roles } = res // note: roles must be a object array! such as: [{id: '1', name: 'editor'}, {id: '2', name: 'developer'}]
store.dispatch('generateRoutes', { roles }).then(accessRoutes => { store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
// 根据roles权限生成可访问的路由表 // 根据roles权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表 router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
}) })
}) })
.catch(err => { .catch(err => {
store.dispatch('resetToken').then(() => { store.dispatch('user/resetToken').then(() => {
Message.error(err) Message.error(err)
next({ path: '/' }) next({ path: '/' })
}) })

View File

@ -1,7 +1,6 @@
import Cookies from 'js-cookie' import Cookies from 'js-cookie'
const app = { const state = {
state: {
sidebar: { sidebar: {
opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true, opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
withoutAnimation: false withoutAnimation: false
@ -9,8 +8,9 @@ const app = {
device: 'desktop', device: 'desktop',
language: Cookies.get('language') || 'en', language: Cookies.get('language') || 'en',
size: Cookies.get('size') || 'medium' size: Cookies.get('size') || 'medium'
}, }
mutations: {
const mutations = {
TOGGLE_SIDEBAR: state => { TOGGLE_SIDEBAR: state => {
state.sidebar.opened = !state.sidebar.opened state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false state.sidebar.withoutAnimation = false
@ -36,8 +36,9 @@ const app = {
state.size = size state.size = size
Cookies.set('size', size) Cookies.set('size', size)
} }
}, }
actions: {
const actions = {
toggleSideBar({ commit }) { toggleSideBar({ commit }) {
commit('TOGGLE_SIDEBAR') commit('TOGGLE_SIDEBAR')
}, },
@ -54,6 +55,10 @@ const app = {
commit('SET_SIZE', size) commit('SET_SIZE', size)
} }
} }
}
export default app export default {
namespaced: true,
state,
mutations,
actions
}

View File

@ -1,17 +1,23 @@
const errorLog = {
state: { const state = {
logs: [] logs: []
}, }
mutations: {
const mutations = {
ADD_ERROR_LOG: (state, log) => { ADD_ERROR_LOG: (state, log) => {
state.logs.push(log) state.logs.push(log)
} }
}, }
actions: {
const actions = {
addErrorLog({ commit }, log) { addErrorLog({ commit }, log) {
commit('ADD_ERROR_LOG', log) commit('ADD_ERROR_LOG', log)
} }
} }
}
export default errorLog export default {
namespaced: true,
state,
mutations,
actions
}

View File

@ -34,18 +34,19 @@ export function filterAsyncRoutes(routes, roles) {
return res return res
} }
const permission = { const state = {
state: {
routes: [], routes: [],
addRoutes: [] addRoutes: []
}, }
mutations: {
const mutations = {
SET_ROUTES: (state, routes) => { SET_ROUTES: (state, routes) => {
state.addRoutes = routes state.addRoutes = routes
state.routes = constantRoutes.concat(routes) state.routes = constantRoutes.concat(routes)
} }
}, }
actions: {
const actions = {
generateRoutes({ commit }, data) { generateRoutes({ commit }, data) {
return new Promise(resolve => { return new Promise(resolve => {
const { roles } = data const { roles } = data
@ -60,6 +61,10 @@ const permission = {
}) })
} }
} }
}
export default permission export default {
namespaced: true,
state,
mutations,
actions
}

View File

@ -1,23 +1,29 @@
import defaultSettings from '@/settings' import defaultSettings from '@/settings'
const { showSettings, tagsView } = defaultSettings const { showSettings, tagsView } = defaultSettings
const settings = { const state = {
state: {
showSettings: showSettings, showSettings: showSettings,
tagsView: tagsView tagsView: tagsView
}, }
mutations: {
const mutations = {
CHANGE_SETTING: (state, { key, value }) => { CHANGE_SETTING: (state, { key, value }) => {
if (state.hasOwnProperty(key)) { if (state.hasOwnProperty(key)) {
state[key] = value state[key] = value
} }
} }
}, }
actions: {
const actions = {
changeSetting({ commit }, data) { changeSetting({ commit }, data) {
commit('CHANGE_SETTING', data) commit('CHANGE_SETTING', data)
} }
} }
export default {
namespaced: true,
state,
mutations,
actions
} }
export default settings

View File

@ -1,9 +1,10 @@
const tagsView = {
state: { const state = {
visitedViews: [], visitedViews: [],
cachedViews: [] cachedViews: []
}, }
mutations: {
const mutations = {
ADD_VISITED_VIEW: (state, view) => { ADD_VISITED_VIEW: (state, view) => {
if (state.visitedViews.some(v => v.path === view.path)) return if (state.visitedViews.some(v => v.path === view.path)) return
state.visitedViews.push( state.visitedViews.push(
@ -69,9 +70,9 @@ const tagsView = {
} }
} }
} }
}
}, const actions = {
actions: {
addView({ dispatch }, view) { addView({ dispatch }, view) {
dispatch('addVisitedView', view) dispatch('addVisitedView', view)
dispatch('addCachedView', view) dispatch('addCachedView', view)
@ -156,6 +157,10 @@ const tagsView = {
commit('UPDATE_VISITED_VIEW', view) commit('UPDATE_VISITED_VIEW', view)
} }
} }
}
export default tagsView export default {
namespaced: true,
state,
mutations,
actions
}

View File

@ -1,16 +1,15 @@
import { login, logout, getInfo } from '@/api/user' import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth' import { getToken, setToken, removeToken } from '@/utils/auth'
const user = { const state = {
state: {
token: getToken(), token: getToken(),
name: '', name: '',
avatar: '', avatar: '',
introduction: '', introduction: '',
roles: [] roles: []
}, }
mutations: { const mutations = {
SET_TOKEN: (state, token) => { SET_TOKEN: (state, token) => {
state.token = token state.token = token
}, },
@ -26,9 +25,9 @@ const user = {
SET_ROLES: (state, roles) => { SET_ROLES: (state, roles) => {
state.roles = roles state.roles = roles
} }
}, }
actions: { const actions = {
// user login // user login
login({ commit }, userInfo) { login({ commit }, userInfo) {
const { username, password } = userInfo const { username, password } = userInfo
@ -73,7 +72,7 @@ const user = {
}, },
// user logout // user logout
Logout({ commit, state }) { logout({ commit, state }) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
logout(state.token).then(() => { logout(state.token).then(() => {
commit('SET_TOKEN', '') commit('SET_TOKEN', '')
@ -99,20 +98,26 @@ const user = {
// 动态修改权限 // 动态修改权限
changeRoles({ commit, dispatch }, role) { changeRoles({ commit, dispatch }, role) {
return new Promise(resolve => { return new Promise(resolve => {
commit('SET_TOKEN', role) const token = role + '-token'
setToken(role) commit('SET_TOKEN', token)
getInfo(role).then(response => { setToken(token)
const data = response.data getInfo(token).then(response => {
commit('SET_ROLES', data.roles) const { data } = response
commit('SET_NAME', data.name) const { roles, name, avatar, introduction } = data
commit('SET_AVATAR', data.avatar) commit('SET_ROLES', roles)
commit('SET_INTRODUCTION', data.introduction) commit('SET_NAME', name)
dispatch('generateRoutes', data) // 动态修改权限后 重绘侧边菜单 commit('SET_AVATAR', avatar)
commit('SET_INTRODUCTION', introduction)
dispatch('permission/generateRoutes', data) // 动态修改权限后 重绘侧边菜单
resolve() resolve()
}) })
}) })
} }
} }
}
export default user export default {
namespaced: true,
state,
mutations,
actions
}

View File

@ -23,7 +23,7 @@ if (checkNeed()) {
// Don't ask me why I use Vue.nextTick, it just a hack. // Don't ask me why I use Vue.nextTick, it just a hack.
// detail see https://forum.vuejs.org/t/dispatch-in-vue-config-errorhandler-has-some-problem/23500 // detail see https://forum.vuejs.org/t/dispatch-in-vue-config-errorhandler-has-some-problem/23500
Vue.nextTick(() => { Vue.nextTick(() => {
store.dispatch('addErrorLog', { store.dispatch('errorLog/addErrorLog', {
err, err,
vm, vm,
info, info,

View File

@ -57,7 +57,7 @@ service.interceptors.response.use(
// cancelButtonText: '取消', // cancelButtonText: '取消',
// type: 'warning' // type: 'warning'
// }).then(() => { // }).then(() => {
// store.dispatch('resetToken').then(() => { // store.dispatch('user/resetToken').then(() => {
// location.reload() // 为了重新实例化vue-router对象 避免bug // location.reload() // 为了重新实例化vue-router对象 避免bug
// }) // })
// }) // })

View File

@ -186,7 +186,7 @@ export default {
setTagsViewTitle() { setTagsViewTitle() {
const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article' const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` }) const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
this.$store.dispatch('updateVisitedView', route) this.$store.dispatch('tagsView/updateVisitedView', route)
}, },
submitForm() { submitForm() {
this.postForm.display_time = parseInt(this.display_time / 1000) this.postForm.display_time = parseInt(this.display_time / 1000)

View File

@ -110,7 +110,7 @@ export default {
}, },
set(lang) { set(lang) {
this.$i18n.locale = lang this.$i18n.locale = lang
this.$store.dispatch('setLanguage', lang) this.$store.dispatch('app/setLanguage', lang)
} }
} }
}, },

View File

@ -136,7 +136,7 @@ export default {
if (valid) { if (valid) {
this.loading = true this.loading = true
// dispatch @/store/modules/user login action // dispatch @/store/modules/user login action
this.$store.dispatch('login', this.loginForm).then(() => { this.$store.dispatch('user/login', this.loginForm).then(() => {
this.loading = false this.loading = false
this.$router.push({ path: this.redirect || '/' }) this.$router.push({ path: this.redirect || '/' })
}).catch(() => { }).catch(() => {

View File

@ -22,7 +22,7 @@ export default {
return this.roles[0] return this.roles[0]
}, },
set(val) { set(val) {
this.$store.dispatch('changeRoles', val).then(() => { this.$store.dispatch('user/changeRoles', val).then(() => {
this.$emit('change') this.$emit('change')
}) })
} }