Table of Contents
What does Vuex do?
What is state management?
Single page state management
vuex (Vue3.2 version)
Multi-page state management
Introduction to vuex store object properties
Methods to obtain store instance objects in Vue3
1. state
2. Mutations
{{this.$store.state.count}}
3. actions
4. getters
{{$store.getters.more20stu}}
{{$store.getters.moreAgestu(18)}}
5. modules
{{$store.state.user.count}}
Home Web Front-end Vue.js How to use Vuex in Vue3

How to use Vuex in Vue3

May 14, 2023 pm 08:28 PM
vue3 vuex

    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 id="this-store-state-count">{{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 id="store-getters-more-stu">{{$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 id="store-getters-more-stu">{{$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 id="store-state-user-count">{{$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!

    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

    vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

    How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

    To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

    How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

    Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

    How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

    The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

    How to use Vue3 reusable components How to use Vue3 reusable components May 20, 2023 pm 07:25 PM

    Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

    How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

    vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

    How to use defineCustomElement to define components in Vue3 How to use defineCustomElement to define components in Vue3 May 28, 2023 am 11:29 AM

    Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

    How to use Vue3 and Element Plus to implement automatic import How to use Vue3 and Element Plus to implement automatic import May 22, 2023 pm 04:58 PM

    1 Introduction 1.1 Purpose ElementPlus uses on-demand introduction to greatly reduce the size of the packaged file. 1.2 The final effect is to automatically generate the components.d.ts file and introduce it into the file. The ElementPlus component automatically generates the components.d.ts file and introduce it into the file. ElementPlusAPI2 Preparation Install ElementPlus#Choose a package manager you like#NPM$npminstallelement-plus--save#Yarn$yarnaddelement-plus#pnpm$pnpminstallelement-plus3 Press

    See all articles