vue3 vuex使用
安装 vuex
npm i vuex@next -S // 安装最新vuex
store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
login_index: 0, // 变量
},
mutations: {
act_login(state, index) { // 修改变量方法
state.login_index = index
}
},
actions: {
},
getters: {
},
modules: {
}
})
main.js 挂载
// main.js
import store from './store' // 导入 vuex
createApp(App).use(store).mount('#app')
get vuex 变量
<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'
let store = useStore()
let sel = computed(() => store.state.login_index)
</script>
调用方法修改 state 变量
<script setup>
import { useStore } from 'vuex'
let store = useStore()
let login = () => {
store.commit('act_login', 10) // 调用方法修改 state 变量
}
</script>