全局变量记录两种方式,一种原生,一种pinia 全局状态管理
版本:
"dependencies": {
"element-plus": "^2.2.17",
"pinia": "^2.0.22",
"vue": "^3.2.39",
"vue-router": "^4.1.5"
},
"devDependencies": {
"@vitejs/plugin-vue": "^3.1.0",
"fast-glob": "^3.2.12",
"vite": "^3.1.0",
"vite-plugin-svg-icons": "^2.0.1"
}
如下图
安装
npm install pinia
全局注册
import { createPinia } from 'pinia'
app.use(createPinia())
获取当前是否为小屏幕设备
import { defineStore } from 'pinia'
export const useSystemInfoStore = defineStore({
/** id 是必填的,并且所有 Store 中唯一。因为Pinia会将它在devtools显示 */
id: 'systemInfoStore',
state: () => ({
mobile: false,
screenWidth: document.body.clientWidth
}),
/** computed 修饰一些值 */
getters: {
/** 获取当前是否为小设备 */
isSmallDevice: (state) => {
if (state.mobile || state.screenWidth < 768) return true
return false
}
},
/** methods 可以做同步 异步都可以 提交state */
actions: {
modifyDevice() {
const moblie = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
this.mobile = moblie ? true : false
this.screenWidth = document.body.clientWidth
}
}
})
更改全局变量
<script setup>
import { onMounted } from 'vue'
import { useSystemInfoStore } from './components/system-info.js'
onMounted(() => {
window.onresize = () => {
return (() => {
useSystemInfoStore().modifyDevice()
})()
}
})
</script>
其他页面使用
<template>
<div>{{nowTime}}</div>{{samllScreen.samllDevice}}
</template>
<script>
//方法一
import {storeToRefs} from 'pinia'
import { useSystemInfoStore } from '../components/system-info.js'
export default {
name: 'menu_layout',
data() {
return {
samllScreen: {
samllDevice: false
}
}
},
created() {
const useSystemInfo = useSystemInfoStore()
const {mobile, screenWidth, isSmallDevice} = storeToRefs(useSystemInfo)
this.samllScreen.samllDevice = isSmallDevice
},
}
</script>
<script>
//方法二 然后直接 this.isSmallDevice 支持响应式的
import { useSystemInfoStore } from '../components/system-info.js'
export default {
name: 'menu_layout',
data() {
return {
samllScreen: ''
}
},
computed: {
/** 建议使用 mapState 用以显示声明;不想声明也可以使用mapStores */
...mapState(useSystemInfoStore, ['isSmallDevice']),
},
}
</script>
<script setup>
//方法三 类似下方使用方式
import { storeToRefs } from 'pinia'
import { useLangStore } from '../../store/lang/lang_store.js'
const useLang = useLangStore()
const { langs } = storeToRefs(useLang)
const lang = langs
</script>
其他全局变量的方法:
// 基本逻辑如下
// main.js
app.config.globalProperties.msg = 'hello'
/** 子页面使用 */
import { getCurrentInstance } from "vue"
console.log( getCurrentInstance()?.appContext.config.globalProperties)