Table of contents
2. Create a new folder store, and create a new file index.js in it
3. Contents of the index.js file:
6. Modify the value of count, which is the same as in vue2:
1. Introduce dependencies:
npm i vuex
2. Create a new folder store, and create a new file index.js in it
3. Contents of the index.js file:
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
4. Introduce in main.js
import store from './store'
5. use
Add count: 0 to the state of store/index.js
In any component file: add the following code:
import { useStore } from "vuex";
export default {
name: "App",
setup() {
// Vue3 有个 composition api 的入口
const store = useStore();// 获取容器
},
};
After getting the container store, get the value of count in Vuex, and get it through store.state.count .
It can be used directly in the template, and the old version can be used at present
If you want the data displayed on the page to change after the field count is changed, you need to introduce the computed attribute of vue
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<h1>Vuex</h1>
<h1>{
{ count }}</h1>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
name: "App",
setup() {
// Vue3 有个 composition api 的入口
const store = useStore(); // 获取容器
// 获取 Vuex 中的 count 的值
console.log("store.state.count", store.state.count);
return {
count: computed(() => store.state.count),
};
},
};
</script>
6. Modify the value of count, which is the same as in vue2:
Add the following code to store/index.js:
mutations: {
add(state, payload) {
state.count += payload
}
},
Modify it by commit in the component that wants to modify the value of count
store.commit('add', 3)