Ape Creation Essay|【Vue five minutes】 Vuex state management summary

Table of contents

foreword

1. What is Vuex

2. Install Vuex

1. Download Vuex.js

2. Introduce vuex.js

3. Usage of Vuex

3. Vuex configuration options 

1, state configuration options

2, getters configuration options 

 3. Mutations configuration options

4, actions configuration options 

5, modules configuration options


foreword

     This is a series of learning, and many other excellent bloggers at station C may also record enough related blog posts. It is stated that this blog post is the witness of a learning process on the way of the blogger himself learning Vue. If there are any similarities, pure It's a coincidence! There is still a lot of learning knowledge in the back. Many senior bigwigs have taught us. We can only say that we are learning and summarizing on the shoulders of our predecessors. There are still many bloggers in station C who record the contents of this book. If you don’t like it, don’t spray it. Just record the details. Well, let's start our learning journey today! !

1. What is Vuex

  This Vuex is a state management mode specially developed for Vue project development. Because our vue components will have their own state, and each data needs to share the required data. We can simply understand that the application of Vuex is a container, which is used to define the data and data processing tools in the application. The core is the store. When the component applies the state in the store, if the state changes, then the corresponding The components will also change, and the data of the components will also be updated.

This state self-management application consists of the following parts:

  • State , the data source that drives the application;
  • Views , which declaratively map state to views;
  • Actions that respond to state changes caused by user input on the view .

 

2. Install Vuex

1. Download Vuex.js

    We can log in to the official website to download, here we provide a link to the official website, you can download it yourself.

Link: Installation | Vuex Vue.js Centralized State Management Solution https://vuex.vuejs.org/zh/installation.html

 The official website provides a teaching method for downloading. You can simply take a look at it. All roads lead to Rome. There are many methods, so you don’t stick to the editor’s blog.

2. Introduce vuex.js

We directly introduce our vue.js on our interface, and then introduce vuex.js. This step is simple, the code is as follows: you can copy it directly.

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

3. Usage of Vuex

   First of all, to use Vuex, then we first need to instantiate an instance of our project through the new keyword, which is a single state tree. Our code syntax for creating the store looks like this:

new Vuex.store({
state:{},   //竹竿天,组件中需要我们共享的数据
mutations:{},//改变状态的唯一办就是提交mutations,同步我们改变的状态
actions:{}  //用于同步更新状态
})

Next, we need to inject our store instance into the Vue root instance;

var vm = new Vue({
el:'#app',
store,
})

Finally, through the store option registered in our root instance, this store instance will be injected into all sub-components under our root component, so that sub-components will access the store data through this.$store. We can understand our understanding of this part through a piece of example code.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Vuex的使用</title>
    

</head>
<body>
    <div id="app">
        <p>姓名:{
   
   {name}}</p>
        <p>性别:{
   
   {gender}}</p>
        <p>年龄:{
   
   {age}}</p>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            name:'丘比特',
            gender:'男',
            age:22
        },
    })
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
            name(state){return this.$store.state.name},
            gender(state){return this.$store.state.gender},
            age(state){return this.$store.state.age},
        }
    })
</script>
</html>

operation result:

We can see that our instance can already display the data in our state.

3. Vuex configuration options 

   We recorded the vue part of the study earlier, and also have the related vue configuration options, so Vuex also has its corresponding part of the configuration options. If you need to see the vue configuration options, you can go to the blogger's homepage to search if you are interested. .

 When creating a store instance, we need to pass in a configuration object, which we will explain one by one.

1, state configuration options

    To add a little knowledge here, the state storage of Vuex responds immediately. When our vue component reads data from the store, if the data changes, the store data on the page will also change.

In our previous example code, we can know that the name data in the state is accessed through "this.$store.state.name". When a component needs to obtain multiple components, all these states are declared as calculations. Attribute computed is a bit cumbersome, because in order to solve the original intention of cumbersome, our Vuex provides a mapState helper function to generate computed properties!

    When using this helper function, you must first introduce this function. The parameters of this auxiliary function are written in two ways: array and object. We can understand it through a piece of example code.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Vuex的使用</title>
    

</head>
<body>
    <div id="app">
        <p>姓名:{
   
   {name}}</p>
        <p>博客:{
   
   {boke}}</p>
        <p>码龄:{
   
   {age}}</p>
        <p>*************************</p>
        <p>姓名:{
   
   {n1}}</p>
        <p>博客:{
   
   {n2}}</p>
        <p>码龄:{
   
   {n3}}</p>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            name:'丘比特',
            boke:'丘比特惩罚陆',
            age:1
        },
    })
    var mapState = Vuex.mapState;
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
        ...mapState(["name","boke","age"]),//mapstate数组的写法
        ...mapState({n1:"name",n2:"boke",n3:"age"})//mapstate对象的写法
        }
    })
</script>
</html>

operation result:

2, getters configuration options 

   In the above store, when it is used, some data will be derived that we need to process. Vuex can allow the "getter" option to be defined in the store. The getter will store our return value according to the dependencies it provides. When the dependency value changes, the getter will also be recalculated. In short, it is calculated with computed properties are the same. We understand our property options through a piece of code.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Vuex的使用</title>
</head>
<body>
    <div id="app">
        <h1>电影:《隐入烟尘》票价</h1>
        <p>票价:{
   
   {total}}</p>
        <p>总票价:{
   
   {totalprice}}</p>
        <img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%253A%252F%252Fdingyue.ws.126.net%252F2022%252F0812%252F3e335b62j00rggmlw001oc000hs00awg.jpg%26thumbnail%3D660x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664263935&t=45b74bdee4889fa5660d0418f1043919" alt="">
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            price:'100',
            num:'2',
        },
        getters:{
            total(state){
                return state.price * state.num;
            }
        }
    })
    var mapGetters = Vuex.mapGetters;
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
        ...mapGetters(['total']),
        ...mapGetters({totalprice:'total'})
        }
    })
</script>
</html>

operation result:

 

 3. Mutations configuration options

   In each mutation there is a string event type and a callback function. Because if we want to modify the data of the store, then we have to submit the mutation, and it is also a synchronization function, so that we can track the changes of each state. There are two ways to submit mutations in our component. We can all use the following code to understand the content of the configuration options of this mutation.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Vuex的使用</title>
</head>
<body>
    <div id="app">
        <h1>{
   
   {num}}</h1>
<button @click="reduce">减5</button>
<button @click="add({n:10})">加5</button>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            num:100,
        },
        mutations:{
            decrement(state){
                state.num--
            },
            increment(state,payload){
                state.num+=payload.n
            },
        },
    })
    var mapState = Vuex.mapState;
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
        ...mapState(["num"])
        },
        methods:{
            reduce(){
                //这里是通过mutation修改store的状态的意思
                this.$store.commit("decrement");
            },
            add(){
                this.$store.commit({type:"increment",n:10});
            }
        }
    })
</script>
</html>

operation result:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Vuex的使用</title>
</head>
<body>
    <div id="app">
        <h1>我想象的中秋国庆放假天数:</h1>
        <h1>{
   
   {num}}</h1>
<button @click="reduce({n:5})">减5</button>
<button @click="add({n:10})">加10</button>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            num:100,
        },
        mutations:{
            decrement(state,payload1){
                state.num-=payload1.n
            },
            increment(state,payload2){
                state.num+=payload2.n
            },
        },
    })
    var mapState = Vuex.mapState;
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
        ...mapState(["num"])
        },
        methods:{
            reduce(){
                //这里是通过mutation修改store的状态的意思
                this.$store.commit({type:"decrement",n:5});
            },
            add(){
                this.$store.commit({type:"increment",n:10});
            }
        }
    })
</script>
</html>

operation result:

We can see the changes in our data by clicking, and of course, we can also go to the Vue 1 part of our background to see the changes in our state data.

4, actions configuration options 

   The configuration options in this section of actions are a bit similar to our previous mutation configuration options, but different from the above mutation, the action submitted is the mutation configuration option, which is more simple and rude, not directly changing our state. The change. Action can contain many asynchronous operations, which can modify the data in the state asynchronously. Asynchronously modifying the state also requires submitting a mutation to achieve the purpose of modification.

   This action function accepts a context object with the same methods and properties as the store instance, so you can submit a mutation to get state or getter data. Let's take a look at the code.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Vuex的使用</title>
</head>
<body>
    <div id="app">
        <h1>我想象的日增资金:</h1>
        <h1>{
   
   {num}}</h1>

<button @click="add()">>+100</button>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    var store = new Vuex.Store({
        state:{
            num:100,
        },
        mutations:{
            increment(state,payload){
                state.num+=payload.n
            },
        },
        actions:{
            async ayscIncrement({commit},payload){
                setTimeout(()=>{
                    commit('increment',payload)
                },1000)
            }
        }
    })
    var mapState = Vuex.mapState;
    var vm = new Vue({
        el:'#app',
        store,
        computed:{
        ...mapState(["num"])
        },
        methods:{
            add(){
                this.$store.dispatch({type:"ayscIncrement",n:100});
            }
        }
    })
</script>
</html>

operation result:

 You can see the results of our demo above. Of course, we can still use the helper function mapAions to simplify the modification. Here you can figure it out for yourself!

5, modules configuration options

   When we use a single component state tree, all the states that can be applied will be grouped into a larger object, but when the application is particularly complex, our store will appear very unfilled. So in order to solve this problem, our Vuex divides the store into many modules modules, so that each module has its own state, mutation, action, etc., which looks more beautiful. We can see what this is all about through the example code.

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Vuex的使用</title>
</head>
<body>
    <div id="app">
        <h1>{
   
   {this.$store.state.store1.num}}</h1>
        <h1>{
   
   {this.$store.state.store2.num}}</h1>
    </div>
</body>

<script src="http://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script>
    const module1 = {
        state:{
            num:100
        },
        getters:{},
        mutations:{},
        actions:{}
    }
    const module2 = {
        state:{
            num:200
        },
        getters:{},
        mutations:{},
        actions:{}
    }
    var store = new Vuex.Store({
        modules:{
            store1:module1,
            store2:module2,
        }
    })
    var vm = new Vue({
        el:'#app',
        store,
    })
</script>
</html>

operation result:

 

Guess you like

Origin blog.csdn.net/Lushengshi/article/details/126568845