使用Pinia代替Vuex进行数据存储

This commit is contained in:
RuoYi
2025-04-23 20:53:28 +08:00
parent fd97380edb
commit 3eca7b1219
15 changed files with 169 additions and 155 deletions

20
App.vue
View File

@@ -1,7 +1,9 @@
<script setup> <script setup>
import { onLaunch } from '@dcloudio/uni-app' import config from './config'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
import { useConfigStore } from '@/store'
import { getCurrentInstance } from "vue" import { getCurrentInstance } from "vue"
import { onLaunch } from '@dcloudio/uni-app'
const { proxy } = getCurrentInstance() const { proxy } = getCurrentInstance()
@@ -11,12 +13,18 @@
// 初始化应用 // 初始化应用
function initApp() { function initApp() {
// 初始化应用配置
initConfig()
// 检查用户登录状态 // 检查用户登录状态
//#ifdef H5 //#ifdef H5
checkLogin() checkLogin()
//#endif //#endif
} }
function initConfig() {
useConfigStore().setConfig(config)
}
function checkLogin() { function checkLogin() {
if (!getToken()) { if (!getToken()) {
proxy.$tab.reLaunch('/pages/login') proxy.$tab.reLaunch('/pages/login')
@@ -24,16 +32,6 @@
} }
</script> </script>
<script>
import config from './config'
export default {
onLaunch: function() {
this.globalData.config = config
}
}
</script>
<style lang="scss"> <style lang="scss">
@import '@/static/scss/index.scss' @import '@/static/scss/index.scss'
</style> </style>

View File

@@ -1,7 +1,7 @@
// 应用全局配置 // 应用全局配置
export default { export default {
baseUrl: 'https://vue.ruoyi.vip/prod-api', // baseUrl: 'https://vue.ruoyi.vip/prod-api',
// baseUrl: 'http://localhost:8080', baseUrl: 'http://localhost:8080',
// 应用信息 // 应用信息
appInfo: { appInfo: {
// 应用名称 // 应用名称

View File

@@ -4,9 +4,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<title></title> <title>RuoYi-App</title>
<!--preload-links-->
<!--app-context-->
</head> </head>
<body> <body>

View File

@@ -35,7 +35,9 @@
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>" "<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
] ]
}, },
"ios" : {}, "ios" : {
"dSYMs" : false
},
"sdkConfigs" : {} "sdkConfigs" : {}
} }
}, },

View File

@@ -40,11 +40,11 @@
<script setup> <script setup>
import { getCodeImg } from '@/api/login' import { getCodeImg } from '@/api/login'
import store from '@/store' import { useConfigStore, useUserStore } from '@/store'
import { ref, getCurrentInstance } from "vue" import { ref, getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance() const { proxy } = getCurrentInstance()
const globalConfig = getApp().globalData.config const globalConfig = useConfigStore().config
const codeUrl = ref("") const codeUrl = ref("")
// 验证码开关 // 验证码开关
const captchaEnabled = ref(true) const captchaEnabled = ref(true)
@@ -101,7 +101,7 @@
// 密码登录 // 密码登录
async function pwdLogin() { async function pwdLogin() {
store.dispatch('Login', loginForm.value).then(() => { useUserStore().login(loginForm.value).then(() => {
proxy.$modal.closeLoading() proxy.$modal.closeLoading()
loginSuccess() loginSuccess()
}).catch(() => { }).catch(() => {
@@ -114,7 +114,7 @@
// 登录成功后,处理函数 // 登录成功后,处理函数
function loginSuccess(result) { function loginSuccess(result) {
// 设置用户信息 // 设置用户信息
store.dispatch('GetInfo').then(res => { useUserStore().getInfo().then(res => {
proxy.$tab.reLaunch('/pages/index') proxy.$tab.reLaunch('/pages/index')
}) })
} }

View File

@@ -44,8 +44,10 @@
</template> </template>
<script setup> <script setup>
const url = getApp().globalData.config.appInfo.site_url import { useConfigStore } from '@/store'
const version = getApp().globalData.config.appInfo.version
const url = useConfigStore().config.appInfo.site_url
const version = useConfigStore().config.appInfo.version
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -38,7 +38,7 @@
<script> <script>
import config from '@/config' import config from '@/config'
import store from "@/store" import { useUserStore } from '@/store'
import { uploadAvatar } from "@/api/system/user" import { uploadAvatar } from "@/api/system/user"
const baseUrl = config.baseUrl const baseUrl = config.baseUrl
@@ -68,7 +68,7 @@
*/ */
data() { data() {
return { return {
imageSrc: store.getters.avatar, imageSrc: useUserStore().avatar,
isShowImg: false, isShowImg: false,
// 初始化的宽高 // 初始化的宽高
cropperInitW: SCREEN_WIDTH, cropperInitW: SCREEN_WIDTH,
@@ -257,7 +257,7 @@
uni.hideLoading() uni.hideLoading()
let data = {name: 'avatarfile', filePath: res.tempFilePath} let data = {name: 'avatarfile', filePath: res.tempFilePath}
uploadAvatar(data).then(response => { uploadAvatar(data).then(response => {
store.commit('SET_AVATAR', baseUrl + response.imgUrl) useUserStore().SET_AVATAR(baseUrl + response.imgUrl)
uni.showToast({ title: "修改成功", icon: 'success' }) uni.showToast({ title: "修改成功", icon: 'success' })
uni.navigateBack() uni.navigateBack()
}) })

View File

@@ -77,13 +77,12 @@
</template> </template>
<script setup> <script setup>
import store from '@/store' import { useUserStore } from '@/store'
import { computed , getCurrentInstance } from "vue" import { computed , getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance() const { proxy } = getCurrentInstance()
const name = store.state.user.name const name = useUserStore().name
const version= getApp().globalData.config.appInfo.version const avatar = computed(() => useUserStore().avatar)
const avatar = computed(() => store.state.user.avatar)
const windowHeight = computed(() => uni.getSystemInfoSync().windowHeight - 50) const windowHeight = computed(() => uni.getSystemInfoSync().windowHeight - 50)
function handleToInfo() { function handleToInfo() {

View File

@@ -31,7 +31,7 @@
</template> </template>
<script setup> <script setup>
import store from '@/store' import { useUserStore } from '@/store'
import { ref, computed , getCurrentInstance } from "vue" import { ref, computed , getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance() const { proxy } = getCurrentInstance()
@@ -51,7 +51,7 @@
function handleLogout() { function handleLogout() {
proxy.$modal.confirm('确定注销并退出系统吗?').then(() => { proxy.$modal.confirm('确定注销并退出系统吗?').then(() => {
store.dispatch('LogOut').then(() => {}).finally(()=>{ useUserStore().logOut().then(() => {}).finally(()=>{
proxy.$tab.reLaunch('/pages/index') proxy.$tab.reLaunch('/pages/index')
}) })
}) })

View File

@@ -1,8 +1,8 @@
import store from '@/store' import { useUserStore } from '@/store'
function authPermission(permission) { function authPermission(permission) {
const all_permission = "*:*:*" const all_permission = "*:*:*"
const permissions = store.getters && store.getters.permissions const permissions = useUserStore().permissions
if (permission && permission.length > 0) { if (permission && permission.length > 0) {
return permissions.some(v => { return permissions.some(v => {
return all_permission === v || v === permission return all_permission === v || v === permission
@@ -14,7 +14,7 @@ function authPermission(permission) {
function authRole(role) { function authRole(role) {
const super_admin = "admin" const super_admin = "admin"
const roles = store.getters && store.getters.roles const roles = useUserStore().roles
if (role && role.length > 0) { if (role && role.length > 0) {
return roles.some(v => { return roles.some(v => {
return super_admin === v || v === role return super_admin === v || v === role

View File

@@ -1,8 +0,0 @@
const getters = {
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name,
roles: state => state.user.roles,
permissions: state => state.user.permissions
}
export default getters

View File

@@ -1,11 +1,7 @@
import { createStore } from "vuex" import { createPinia } from 'pinia'
import user from '@/store/modules/user'
import getters from './getters'
const store = createStore({ const pinia = createPinia()
modules: {
user export default pinia
}, export { useUserStore } from './modules/user'
getters export { useConfigStore } from './modules/config'
})
export default store

13
store/modules/config.js Normal file
View File

@@ -0,0 +1,13 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useConfigStore = defineStore('config', () => {
const config = ref()
const setConfig = (val) => {
config.value = val
}
return {
config,
setConfig
}
})

View File

@@ -2,46 +2,48 @@ import config from '@/config'
import storage from '@/utils/storage' import storage from '@/utils/storage'
import constant from '@/utils/constant' import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate" import { isHttp, isEmpty } from "@/utils/validate"
import { login, logout, getInfo } from '@/api/login' import { getInfo, login, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth' import { getToken, removeToken, setToken } from '@/utils/auth'
import defAva from '@/static/images/profile.jpg' import defAva from '@/static/images/profile.jpg'
import { ref } from 'vue'
import { defineStore } from 'pinia'
const baseUrl = config.baseUrl const baseUrl = config.baseUrl
const user = { export const useUserStore = defineStore('user', () => {
state: { const token = ref(getToken())
token: getToken(), const id = ref(storage.get(constant.id))
name: storage.get(constant.name), const name = ref(storage.get(constant.name))
avatar: storage.get(constant.avatar), const avatar = ref(storage.get(constant.avatar))
roles: storage.get(constant.roles), const roles = ref(storage.get(constant.roles))
permissions: storage.get(constant.permissions) const permissions = ref(storage.get(constant.permissions))
},
mutations: { const SET_TOKEN = (val) => {
SET_TOKEN: (state, token) => { token.value = val
state.token = token }
}, const SET_ID = (val) => {
SET_NAME: (state, name) => { id.value = val
state.name = name storage.set(constant.id, val)
storage.set(constant.name, name) }
}, const SET_NAME = (val) => {
SET_AVATAR: (state, avatar) => { name.value = val
state.avatar = avatar storage.set(constant.name, val)
storage.set(constant.avatar, avatar) }
}, const SET_AVATAR = (val) => {
SET_ROLES: (state, roles) => { avatar.value = val
state.roles = roles storage.set(constant.avatar, val)
storage.set(constant.roles, roles) }
}, const SET_ROLES = (val) => {
SET_PERMISSIONS: (state, permissions) => { roles.value = val
state.permissions = permissions storage.set(constant.roles, val)
storage.set(constant.permissions, permissions) }
const SET_PERMISSIONS = (val) => {
permissions.value = val
storage.set(constant.permissions, val)
} }
},
actions: {
// 登录 // 登录
Login({ commit }, userInfo) { const loginAction = (userInfo) => {
const username = userInfo.username.trim() const username = userInfo.username.trim()
const password = userInfo.password const password = userInfo.password
const code = userInfo.code const code = userInfo.code
@@ -49,16 +51,16 @@ const user = {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
login(username, password, code, uuid).then(res => { login(username, password, code, uuid).then(res => {
setToken(res.token) setToken(res.token)
commit('SET_TOKEN', res.token) SET_TOKEN(res.token)
resolve() resolve()
}).catch(error => { }).catch(error => {
reject(error) reject(error)
}) })
}) })
}, }
// 获取用户信息 // 获取用户信息
GetInfo({ commit, state }) { const getInfoAction = () => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
getInfo().then(res => { getInfo().then(res => {
const user = res.user const user = res.user
@@ -66,29 +68,31 @@ const user = {
if (!isHttp(avatar)) { if (!isHttp(avatar)) {
avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
} }
const userid = (isEmpty(user) || isEmpty(user.userId)) ? "" : user.userId
const username = (isEmpty(user) || isEmpty(user.userName)) ? "" : user.userName const username = (isEmpty(user) || isEmpty(user.userName)) ? "" : user.userName
if (res.roles && res.roles.length > 0) { if (res.roles && res.roles.length > 0) {
commit('SET_ROLES', res.roles) SET_ROLES(res.roles)
commit('SET_PERMISSIONS', res.permissions) SET_PERMISSIONS(res.permissions)
} else { } else {
commit('SET_ROLES', ['ROLE_DEFAULT']) SET_ROLES(['ROLE_DEFAULT'])
} }
commit('SET_NAME', username) SET_ID(userid)
commit('SET_AVATAR', avatar) SET_NAME(username)
SET_AVATAR(avatar)
resolve(res) resolve(res)
}).catch(error => { }).catch(error => {
reject(error) reject(error)
}) })
}) })
}, }
// 退出系统 // 退出系统
LogOut({ commit, state }) { const logOutAction = () => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
logout(state.token).then(() => { logout(token.value).then(() => {
commit('SET_TOKEN', '') SET_TOKEN('')
commit('SET_ROLES', []) SET_ROLES([])
commit('SET_PERMISSIONS', []) SET_PERMISSIONS([])
removeToken() removeToken()
storage.clean() storage.clean()
resolve() resolve()
@@ -97,7 +101,17 @@ const user = {
}) })
}) })
} }
}
}
export default user return {
token,
id,
name,
avatar,
roles,
permissions,
SET_AVATAR,
login: loginAction,
getInfo: getInfoAction,
logOut: logOutAction
}
})

View File

@@ -1,8 +1,8 @@
const constant = { const constant = {
avatar: 'vuex_avatar', avatar: 'user_avatar',
name: 'vuex_name', name: 'user_name',
roles: 'vuex_roles', roles: 'user_roles',
permissions: 'vuex_permissions' permissions: 'user_permissions'
} }
export default constant export default constant