Vue Official: State Management Tool
State that needs to be shared among multiple components, and it is responsive, one change, all changes .
For example, some globally used status information: user login status, user name, geographical location information, items in the shopping cart, etc.
At this time we need such a tool. Global state management, Vuex is such a tool.
View–>Actions—>State
The view layer (view) triggers the operation (action) changes the state (state) and responds back to the view Layer (view)
store/index.js Create store object and export store
import { createStore } from 'vuex' export default createStore({ state: { }, mutations: { }, actions: { }, modules: { } })
main.js Import and use
... import store from './store' ... app.use(store)
vue2 You can get the instance object of the store through this.$store.xxx.
The setup in vue3 is executed before beforecreate and created. At this time, the vue object has not been created yet, and there is no previous this, so here we need to use another method to obtain the store object.
import { useStore } from 'vuex' // 引入useStore 方法 const store = useStore() // 该方法用于返回store 实例 console.log(store) // store 实例对象
Where to store data
state: { count: 100, num: 10 },
Usage: The usage method is roughly the same as the version in vue2.x, through the $store.state.property name Get the attributes in state.
//template中 <span>{{$store.state.count}}</span> <span>{{$store.state.num}}</span>
You can perform data changes directly in the state, but Vue does not recommend this. Because for the Vue development tool devtools, if data changes are made directly in the state, devtools cannot track it. In vuex, it is hoped that data changes can be performed through actions (asynchronous operations) or mutations (synchronous operations), so that data changes can be directly observed and recorded in devtools, making it easier for developers to debug.
In addition, when adding attributes or deleting objects in the state in vue3, you no longer need to use vue.set() or vue.delete() to perform responsive processing of the object. You can directly new The added object properties are already responsive.
The only way to update Vuex's store status is to submit mutations
Synchronization operations can be performed directly in mutations
mutations mainly include Part 2:
String event type (type)
A ** callback function (handler) ** The callback function’s One parameter is state
mutations: { // 传入 state increment (state) { state.count++ } }
Triggered by $store.commit('method name') in template
In vue3.x, you need to get the ** store instance If so, you need to call a function like useStore **, and import the parameters and parameter passing methods of
// 导入 useStore 函数 import { useStore } from 'vuex' const store = useStore() store.commit('increment')
mutation in vuex.
mution receives parameters and writes them directly in the defined method. The passed parameters can be accepted inside
// ...state定义count mutations: { sum (state, num) { state.count += num } }
Parameters are passed through the commit payload
Use store.commit('function name in mutation', 'parameters that need to be passed') to add in commit Passing parameters in the form of parameters
<h3>{{this.$store.state.count}}</h3> <button @click="add(10)">++</button> ... <script setup> // 获取store实例,获取方式看上边获取store实例方法 const add = (num) => { store.commit('sum', num) } </script>
Mutation submission style
As mentioned earlier, mutation mainly consists of two parts: type and callback function, and parameters are passed in the form of commit payload. (Submit), below we can
submit the mutation in this way
const add = (num) => { store.commit({ type: 'sum', // 类型就是mution中定义的方法名称 num }) } ... mutations: { sum (state, payload) { state.count += payload.num } }
Asynchronous operations are performed in the action and then passed to mutation
The basic usage of action is as follows:
The default parameter of the method defined in action is ** context context**, which can be understood as the store object
Get the store through the context context object. Trigger the method in the mutation through commit to complete the asynchronous operation
... mutations: { sum (state, num) { state.count += num } }, actions: { // context 上下文对象,可以理解为store sum_actions (context, num) { setTimeout(() => { context.commit('sum', num) // 通过context去触发mutions中的sum }, 1000) } },
Call the sum_action method defined in the action through dispatch in the template
// ...template store.dispatch('sum_actions', num)
Use promise to complete the asynchronous operation and notify the component asynchronously The execution succeeds or fails.
// ... const addAction = (num) => { store.dispatch('sum_actions', { num }).then((res) => { console.log(res) }).catch((err) => { console.log(err) }) }
The sun_action method returns a promise. When the accumulated value is greater than 30, it will no longer be accumulated and an error will be thrown.
actions: { sum_actions (context, payload) { return new Promise((resolve, reject) => { setTimeout(() => { // 通过 context 上下文对象拿到 count if (context.state.count < 30) { context.commit('sum', payload.num) resolve('异步操作执行成功') } else { reject(new Error('异步操作执行错误')) } }, 1000) }) } },
Similar to the computed properties of components
import { createStore } from 'vuex' export default createStore({ state: { students: [{ name: 'mjy', age: '18'}, { name: 'cjy', age: '22'}, { name: 'ajy', age: '21'}] }, getters: { more20stu (state) { return state.students.filter(item => item.age >= 20)} } })
Use the input of calling the $store.getters.method name
//...template <h3>{{$store.getters.more20stu}}</h3> // 展示出小于20岁的学生
getters Parameters, getters can receive two parameters, one is state, and the other is its own getters, and calls its own existing methods.
getters: { more20stu (state, getters) { return getters.more20stu.length} }
Parameters and parameter passing methods of getters
The above are the two fixed parameters of getters. If you want to pass parameters to getters, let them filter people who are greater than age. , you can do this
Return a function that accepts Age and handles
getters: { more20stu (state, getters) { return getters.more20stu.length}, moreAgestu (state) { return function (Age) { return state.students.filter(item => item.age >= Age ) } } // 该写法与上边写法相同但更简洁,用到了ES6中的箭头函数,如想了解es6箭头函数的写法 // 可以看这篇文章 https://blog.csdn.net/qq_45934504/article/details/123405813?spm=1001.2014.3001.5501 moreAgestu_Es6: state => { return Age => { return state.students.filter(item => item.age >= Age) } } }
Use
//...template <h3>{{$store.getters.more20stu}}</h3> // 展示出小于20岁的学生{{$store.getters.moreAgestu(18)}}
// 通过参数传递, 展示出年龄小于18的学生
When the application becomes complex , as more variables are managed in the state, the store object may become quite bloated.
In order to solve this problem, vuex allows us to divide the store into modules, and each module has its own state, mutation, action, getters, etc.
In the store file Create a new modules folder
You can create a single module in modules, and each module handles the functions of one module
store/modules/user.js 处理用户相关功能
store/modules/pay.js 处理支付相关功能
store/modules/cat.js 处理购物车相关功能
// user.js模块 // 导出 export default { namespaced: true, // 为每个模块添加一个前缀名,保证模块命明不冲突 state: () => {}, mutations: {}, actions: {} }
最终通过 store/index.js 中进行引入
// store/index.js import { createStore } from 'vuex' import user from './modules/user.js' import user from './modules/pay.js' import user from './modules/cat.js' export default createStore({ modules: { user, pay, cat } })
在template中模块中的写法和无模块的写法大同小异,带上模块的名称即可
<h3>{{$store.state.user.count}}</h3>
store.commit('user/sum', num) // 参数带上模块名称 store.dispatch('user/sum_actions', sum)
The above is the detailed content of How to use Vuex in Vue3. For more information, please follow other related articles on the PHP Chinese website!