创建store文件夹,
文件夹下创建index.js 创建store对象并导出store
import { createStore } from 'vuex'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
main.js 全局引入并使用store
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
页面内使用
import { useStore } from 'vuex' // 引入useStore 方法
const store = useStore() // 该方法用于返回store 实例
//mutations 方法调用
store.commit('方法名','参数')
store.commit('user/sum', num) // 参数带上模块名称
//actions 方法调用
store.dispatch('方法名'', '参数')
store.dispatch('user/sum_actions', sum)// 参数带上模块名称
//页面渲染
<h2>{{$store.state.count}}</h2>
全局数据监听
import { watch ,computed } from 'vue';
// 获取监听的vuex数据
const getShowTask = computed(()=>{
//返回的是ref对象
return store.state.方法名;
})
// 监听数据变化 请求接口
watch(
getShowTask, (newVal, oldVal) => {
//参数变化 调用方法
console.log('newVal, oldVal', newVal, oldVal)
}, {immediate:true,deep:true}
);
网友评论