前言
因为使用的是uniapp和vue3,不知如何使用vuex,这篇文章也是我的学习笔记。
首先大家要对vuex有一定的了解,废话不说上代码
根目录store/index.js
import {
createStore
} from 'vuex'
console.log(createStore)
export default createStore({
state: {
isLogin: true
},
mutations: {
// 定义mutations,用于修改状态
IsLogin (state, type) {
state.isLogin = type
}
},
actions: {},
getters: {},
modules: {}
})
main.js
import App from './App'
import Store from './store'
// #ifdef VUE3
import { createSSRApp } from 'vue'
console.log(createSSRApp)//源码这里不过多介绍,有兴趣的伙伴可自行研究
export function createApp () {
const app = createSSRApp(App)
app.use(Store)
return {
app
}
}
// #endif
这里就挂载完毕,直接使用就可以
原文链接:https://blog.csdn.net/Marlene_Jiang/article/details/122821318
调用vuex里的方法
这里是我自己整理出来,方便日后查看,不会使用的小伙伴可以自行选择查看
Mutation
import vuex from 'vuex';
import Store from '@/store/index.js';
export default {
components: {
Store,
},
data() {
return {}
},
onLoad() {
let str = false;
Store.commit('IsLogin',str);//调动mutations里面定义的方法
console.log(this.$store.state.isLogin)
},
methods: {}
}
Action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
让我们来注册一个简单的 action:
store/index.js(这么写)
export default createStore({
state: {
isLogin: true
},
mutations: { //Mutation 必须是同步函数
IsLogin (state) { //用于修改状态
state.isLogin = !state.isLogin
}
},
actions: {
IsLogin (context) { //用于修改状态
context.commit('IsLogin')
}
},
getters: {},
modules: {}
})
组件中使用
Store.dispatch('IsLogin')