1:报错原因:const store = xxxStore()在app.use(createPinia())之前执行了,所以才报这个错误
2:解决方案如下:
1:新建一个js或者ts文件
export let list: any[] = []
export function add(fn: any): void {
list.push(fn)
}
export function implement(): void {
list.forEach(item => item())
list = []
}
2:然后直接看代码把,我也懒得打字了
import '@/assets/root.css'
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
import {implement} from "@/utils/store"
import '@/utils/resize'
app.use(createPinia())
implement()
app.use(router)
app.mount('#app')
其中,这个 import '@/utils/resize'
,我执行的主要代码是在这个文件里面的,现在我把它正常引入引来main.ts里面,前提是在app.use(createPinia())
之前引入,最后看下resize.ts下的代码
import {add} from "@/utils/store"
import {menusStore} from "@/stores/counter"
import {storeToRefs} from "pinia";
add((): void => {
const store = menusStore()
const {showMenu} = storeToRefs(store)
const {retract} = store
function execute(): void {
const currentWidth: number = window.innerWidth
if ((currentWidth <= 990 && showMenu.value) || (currentWidth > 990 && !showMenu.value)) {
retract()
}
}
// 自动执行一次
execute()
window.addEventListener('resize', function (): void {
execute()
});
})
超级简陋版的emit/on思想