foreword
The last article told you what is Vuex and the core features of Vuex. This article will show you how to use Vuex in actual projects.
Vuex defines state
As shown in the figure below, we reference two subcomponents in App.vue.
Then we define a data in the store so that both components can access
store/index.js
import {
createStore } from 'vuex'
export default createStore({
state: {
things:[
{
name: "张三", age:"18"},
{
name: "李四", age:"17"},
{
name: "王五", age:"20"},
]
},
mutations: {
},
actions: {
},
modules: {
}
})
Select Vuex when creating a project, and there will be a store file after the project is initialized. Because it is automatically mounted globally in main.js, we can directly access
one.vue in the component: get the value directly through $store.state.things
<template>
<div class="one">
组件一
<ul>
<li v-for="item in $store.state.things" :key="item">
<span>{
{
item.name}}</span>
<span>{
{
item.age}}</span>
</li>
</ul>
</div>
</template>
In this way, the value is successfully obtained, and the second component is the same:
vuex computed property
The above is that the value can be obtained through $store.state.things directly in the template of the page, but often we need to monitor the value, which is located in computed, but the value cannot be obtained by the above method in the script. Let’s see how accomplish:
one.vue:
<template>
<div class="one">
组件一
<ul>
<li v-for="item in things" :key="item">
<span>{
{
item.name}}</span>
<span>{
{
item.age}}</span>
</li>
</ul>
</div>
</template>
<script setup>
import {
computed } from "vue"
import {
useStore } from "vuex"
const store = useStore()
const things = computed(() => store.state.things)
</script>
We need to introduce the useStore provided by vuex, and use it to instantiate a store object. Then you can access the value through store.state.things
Get global state through getter
Above we talked about obtaining the global state through the state, let's see how to obtain the global state through the getter
Create getters in store/index.js:
import {
createStore } from 'vuex'
export default createStore({
state: {
things:[
{
name: "张三", age:"18"},
{
name: "李四", age:"17"},
{
name: "王五", age:"20"},
]
},
getters: {
getProducts: (state) => {
return state.things
}
},
mutations: {
},
actions: {
},
modules: {
}
})
Then in the template of component one, we can get the value through $store.getters.getProducts. So what's the difference between getters and state? In getters, we can process the data:
a new resetProducts method is added below, and ** is added before and after the name
getters: {
getProducts: (state) => {
return state.things
},
resetProducts: (state) => {
return state.things.map((things) => {
return {
name: `**${
things.name}**`
}
})
}
},
Then in component one, we use $store.getters.resetProducts to get the value.
In this way, we can uniformly fine-tune the initial data in getters to facilitate the use of components