Home > Web Front-end > Vue.js > body text

How to use Vuex in Vue3

王林
Release: 2023-05-14 20:28:04
forward
2177 people have browsed it

    What does Vuex do?

    Vue Official: State Management Tool

    What is state management?

    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.

    Single page state management

    View–>Actions—>State

    The view layer (view) triggers the operation (action) changes the state (state) and responds back to the view Layer (view)

    vuex (Vue3.2 version)

    store/index.js Create store object and export store

    import { createStore } from 'vuex'
    
    export default createStore({
      state: {
      },
      mutations: {
      },
      actions: {
      },
      modules: {
      }
    })
    Copy after login

    main.js Import and use

    ...
    import store from './store'
    ...
    app.use(store)
    Copy after login

    Multi-page state management

    How to use Vuex in Vue3

    Introduction to vuex store object properties

    Methods to obtain store instance objects in Vue3

    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 实例对象
    Copy after login
    1. state

    Where to store data

    state: {
      count: 100,
      num: 10
    },
    Copy after login

    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>
    Copy after login

    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.

    2. Mutations

    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:

    1. String event type (type)

    2. A ** callback function (handler) ** The callback function’s One parameter is state

    mutations: {
      // 传入 state
      increment (state) {
        state.count++
      }
    }
    Copy after login

    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 &#39;vuex&#39;
    const store = useStore()
    store.commit(&#39;increment&#39;)
    Copy after login

    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
      }
    }
    Copy after login

    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(&#39;sum&#39;, num)
    }
    </script>
    Copy after login

    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: &#39;sum&#39;,  // 类型就是mution中定义的方法名称
        num
      })
    }
    
    ...
    mutations: {
      sum (state, payload) {
        state.count += payload.num
      }
    }
    Copy after login
    3. actions

    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(&#39;sum&#39;, num)  // 通过context去触发mutions中的sum
        }, 1000)
      }
    },
    Copy after login

    Call the sum_action method defined in the action through dispatch in the template

    // ...template
    store.dispatch(&#39;sum_actions&#39;, num)
    Copy after login

    Use promise to complete the asynchronous operation and notify the component asynchronously The execution succeeds or fails.

    // ...
    const addAction = (num) => {
      store.dispatch(&#39;sum_actions&#39;, {
        num
      }).then((res) => {
        console.log(res)
      }).catch((err) => {
        console.log(err)
      })
    }
    Copy after login

    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(&#39;sum&#39;, payload.num)
                resolve(&#39;异步操作执行成功&#39;)
              } else {
                reject(new Error(&#39;异步操作执行错误&#39;))
              }
            }, 1000)
          })
        }
      },
    Copy after login
    4. getters

    Similar to the computed properties of components

    import { createStore } from &#39;vuex&#39;
    
    export default createStore({
      state: {
        students: [{ name: &#39;mjy&#39;, age: &#39;18&#39;}, { name: &#39;cjy&#39;, age: &#39;22&#39;}, { name: &#39;ajy&#39;, age: &#39;21&#39;}]
      },
      getters: {
        more20stu (state) { return state.students.filter(item => item.age >= 20)}
      }
    })
    Copy after login

    Use the input of calling the $store.getters.method name

    //...template
    <h3>{{$store.getters.more20stu}}</h3> // 展示出小于20岁的学生
    Copy after login

    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}
    }
    Copy after login

    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)
        }
      }
    }
    Copy after login

    Use

    //...template
    <h3>{{$store.getters.more20stu}}</h3> // 展示出小于20岁的学生
    

    {{$store.getters.moreAgestu(18)}}

    // 通过参数传递, 展示出年龄小于18的学生
    Copy after login
    5. modules

    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: {}
    }
    Copy after login

    最终通过 store/index.js 中进行引入

    // store/index.js
    import { createStore } from &#39;vuex&#39;
    import user from &#39;./modules/user.js&#39;
    import user from &#39;./modules/pay.js&#39;
    import user from &#39;./modules/cat.js&#39;
    export default createStore({
      modules: {
        user,
        pay,
        cat
      }
    })
    Copy after login

    在template中模块中的写法和无模块的写法大同小异,带上模块的名称即可

    <h3>{{$store.state.user.count}}</h3>
    Copy after login
    store.commit(&#39;user/sum&#39;, num) // 参数带上模块名称
    store.dispatch(&#39;user/sum_actions&#39;, sum)
    Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template