Seven essential skills, Vuex

This time has been writing with vue project, vuex Yihuhuhuapiao will be used in the project, but there is always a feeling of hazy. I decided to get to know it thoroughly.

I watched an afternoon of official documents, as well as information, only to find vuex so easy!

As a circle of people, decided to look at the output file, if you read this article carefully to ensure that you master on vuex.

 

I put my code is uploaded to github, you may need to pull off: GitHub

 

Let me talk about what vuex in the end is?

vuex is a specially developed for the vue.js application state management.

This state we can be understood as properties in the data, we need to share some of the other component.

In other words, we need to share data, use vuex unified centralized management.

 

vuex, there are five basic default object:

  • state: storing state (variable)
  • getters: to re-compile the previous data acquisition, can be understood as the calculation of state property. We use the $ sotre.getters.fun in the component ()
  • mutations: modified state, and is synchronous. Use $ store.commit ( '', params) in the assembly. This component of our custom event similar.
  • actions: asynchronous operation. Is used in the assembly $ store.dispath ( '')
  • modules: store sub-module, in order to develop large-scale projects to facilitate the management and use of state. We will not explain here, and with them the same as above.

 

 

Here we started, step by step using vuex

 

 

1, first create a vue-cli project

Execute the following command to create an app project (where you can also use other non webpack templates, as well as non-app name)

vue init webpack app

2. Once created, we move to the next folder, and run the project

cd app / 
altitude run dev

Next we create a vuex folder under the src directory

Store.js and creates a file in the folder vuex

Folder directory looks like this

 

3, we have not yet introduced vuex, we need to first download vuex, and introduced it

To ensure we are in our program, enter the following command at the command line, install vuex

npm install vuex --save

4. After the installation is successful, we can have fun in our vuex in the store.js!

In store.js file, the introduction and use vuex vuex, where attention to my variable name is uppercase Vue and Vuex 

Copy the code
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    count: 0
}

export default new Vuex.Store({
    state
})
Copy the code

Next, the introduction of the store in main.js

Copy the code
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store' // 引入store
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})
Copy the code

While I count that we can use our property as defined in any one component.

Here we use it in helloWorld, the removal of unused labels helloworld.vue

<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
  </div>
</template>

We just open a browser to run the project, you can see has been used successful!

And vue development tools, we can see that we define the variable count

At this point, less than half have been successful! vuex very simple, right?

Recall that we only need to download and install using vuex, defined state object store.js our definition, and exposed to.

Use our store.js in main.js in (reference here is to prevent the various components, as main.js, there are examples of our new Vue ah!)

 

Now that we have used vuex in the state, then how do we operate this value? Yes! With mutations and actions

We continue store.js file

We define the mutations in sotre.js object that there are two methods, mutations inside the parameters, the first default state, next to custom parameters.

We define two mutations in methods for increasing and decreasing, and sets a parameter n, the default value is 0, then use it in the Vuex.Store

Copy the code
/ ** 
 * mutations placed inside the operation state is the way we object attributes 
 * / 
const = {mutations 
    mutationsAddCount (state, n-= 0) { 
        return (n-state.count + =) 
    }, 
    mutationsReduceCount (state, n-= 0) { 
        return (state.count - = n-) 
    } 
} 
Export Vuex.Store new new default ({ 
    State, 
    mutations 
})
Copy the code

Then we helloWorld.vue using this method

Remember how we used mutations in the components it? It is very similar and custom events

Copy the code
<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
    <div>
      <button @click="handleAddClick(10)">增加</button>
      <button @click="handleReduceClick(10)">减少</button>
    </div>
  </div>
</template>
Copy the code
Copy the code
methods: {
    handleAddClick(n){
      this.$store.commit('mutationsAddCount',n);
    },
    handleReduceClick(n){
      this.$store.commit('mutationsReduceCount',n);
    }
  }
Copy the code

Browser to look at how effective!

We can see that whenever a triggering event, we can see the way we trigger mutations, as well as parameters vue development tools

perfect!

 

Then there is the actions, actions that asynchronous operation

Creating actions object, and use

Here I use two different methods of two parameters, a context, which is a parameter and store objects having the same object attributes. In the second function, I was directly used the method commit this object.

With everyone trying to be difficult hi

Copy the code
const actions = {
    actionsAddCount(context, n = 0) {
        console.log(context)
        return context.commit('mutationsAddCount', n)
    },
    actionsReduceCount({ commit }, n = 0) {
        return commit('mutationsReduceCount', n)
    }
}
export default new Vuex.Store({
    state,
    mutations,
    actions
})
Copy the code

In the helloWorld.vue

In the methods, the addition of two methods to trigger the use dispath

<div> asynchronous operation </ div> 
  <div> 
    < "(10) handleActionsAdd" Button @ the Click => Asynchronous increase </ Button> 
    <Button @ the Click = "handleActionsReduce (10)"> Asynchronous reduction </ Button> 
  </ div>
Copy the code
handleActionsAdd(n){
      this.$store.dispatch('actionsAddCount',n)
    },
    handleActionsReduce(n){
      this.$store.dispatch('actionsReduceCount',n)
    }
Copy the code

Look into the browser how effective!

The final step is getters

We generally use getters to get our state, because it is considered a state of computing property

Copy the code
const getters = {
    getterCount(state, n = 0) {
        return (state.count += n)
    }
}
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})
Copy the code
<h4>{{count}}</h4>
const getters = {
    getterCount(state) {
        return (state.count += 10)
    }
}

getters regarded as a very simple.

Here, if all understand the, vuex you have no pressure.

But vuex official gave us an easier way to use vuex, that is, {mapState, mapMutations, mapActions, mapGetters}

As long as we get to know the basis of the above, these are alone, we write nothing but respect.

It's that simple, here we use es6 expansion operator. If you are not familiar with the students or to see Ruan Yifeng Great God "Es6 Standard Getting Started" book, I read, benefited!

Copy the code
<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    ...mapMutations({
      handleAddClick: 'mutationsAddCount',
      handleReduceClick: 'mutationsReduceCount'
    }),
    ...mapActions({
      handleActionsAdd: 'actionsAddCount',
      handleActionsReduce: 'actionsReduceCount'
    })
    // handleAddClick(n){
    //   this.$store.commit('mutationsAddCount',n);
    // },
    // handleReduceClick(n){
    //   this.$store.commit('mutationsReduceCount',n);
    // },
    // handleActionsAdd(n){
    //   this.$store.dispatch('actionsAddCount',n)
    // },
    // handleActionsReduce(n){
    //   this.$store.dispatch('actionsReduceCount',n)
    // }
  },
  computed: {
    count(){
      return this.$store.getters.getterCount
    }
  }
}
</script>
Copy the code

 

Similarly, getters and state can also be used mapState, mapGetters

 

If you are more lazy, we can use the array, not the object or objects inside a shorthand way es6

Like This

Guess you like

Origin www.cnblogs.com/qdwz/p/11712096.html