例子为切换主题时触发监听方法 逻辑都是一样的可以根据自己不同需求修改
一、创建js文件 theme.js
const state = () => ({
switchTheme: null,
dataTheme: ''
})
const actions = {
switchThemeFun({ state }, a) {
if (typeof (state.switchTheme) === 'function') {//不加判断在离开页面时注销监听之后会报错
state.switchTheme(a)
} else {
state.switchTheme = null
}
state.dataTheme = a
}
}
const mutations = {
setSwitchThemeFun(state, callback) {
if (typeof (callback) === 'function') {
state.switchTheme = callback
} else {
state.switchTheme = null
}
},
}
export default {
namespaced: true,
state,
actions,
mutations,
}
二 在store index.js 中引入
import theme from './modules/theme'
function loadModules() {
const modules = {
theme
}
return modules
}
const store = createStore({
modules: loadModules(),
plugins: [
],
})
export function loadStore(app) {
app.use(store)
return store
}
export default store
触发页面中使用
//在触发的页面中添加
<template>
<button @click='switchTheme'>
</button>
</template>
<script setup>
import { useStore } from 'vuex'
const store = useStore()
function switchTheme() {
store.dispatch('theme/switchThemeFun', 'dark')
}
</script>
监听页面中使用
//在需要监听的页面中添加
<template>
<div>
</div>
</template>
<script setup>
import {nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import { useStore } from 'vuex'
const store = useStore()
store.commit('theme/setSwitchThemeFun',(i)=>{
// console.log(i); 触发时的参数
})
onUnmounted(()=>{
console.log('离开页面或组件时注销监听');
store.commit('theme/setSwitchThemeFun',null)
})
</script>