Ten power project front-end, state management Vuex (IX)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Eknaij/article/details/96480114

A, Vuex Profile

Vuex is a specially developed for Vue.js application state management. It uses the status of all components centralized storage management application, and a corresponding state rules to ensure a predictable manner changed.
Quick appreciated: Each component has its own attribute data, encapsulated in data (), the data between each component is completely isolated, are private. If we need individual components can access to data, or can exchange data between the various components needed, which requires a separate storage area to store public property. This is the state management problem to be solved.

Second, Quick Start

1. engineering structures

Cmd Create a new project with a template-based webpack

# 创建一个基于 webpack 模板的新项目
vue init webpack vuexdemo
# 安装依赖
cd vuexdemo
npm install
cnpm install --save vuex
#运行
npm run dev

2. Read the status value

The heart of every Vuex application is to store (warehouse). "Store" is basically a container that contains most of the state (state) of your application.
Implementation steps:
Open vuexdemo with CS
(1) create a store under src, created under the store index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		count: 0
	}
})
export default store

(2) modify main.js, store and load the introduction

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
	el: '#app',
	router,
	store,
	components: { App },
	template: '<App/>'
})

(3) modify the components \ HelloWorld.vue

<template>
	<div>
		{{$store.state.count}}
		<button @click="showCount">测试</button>
	</div>
	</template>
<script>
export default {
	methods:{
		showCount(){
			console.log(this.$store.state.count)
		}
	}
}
</script>

Run the following results can be seen
Here Insert Picture Description

3. Change the value of state

You can not directly change the state of the store. The only way to change the status of the store is explicitly commit (commit) mutation. So that we can easily track changes in each state, so that we can achieve some tools to help us better understand our application.
(1) modify the store / index.js, defined mutation increased

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})
export default store

(2) modify the components \ HelloWorld.vue, call the mutation

<template>
	<div>
		{{$store.state.count}}
		<button @click="addCount">测试</button>
	</div>
</template>
<script>
export default {
	methods:{
		addCount(){
      this.$store.commit('increment')
			console.log(this.$store.state.count)
		}
	}
}
</script>

Test: run the project, click the Test button, we will see the console and page output increasing numbers
Here Insert Picture Description
Here Insert Picture Description

4. Test shared state value

If another page, I can read just state HelloWorld operation in the value of it? We are going to do a test
(1) create show.vue in components

<template>
    <div>
        show: {{$store.state.count}}
    </div>
</template>

(2) modify the route setting router / index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Show from '@/components/Show'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/show',
      name: 'Show',
      component: Show
    }
  ]
})

Test: HelloWorld page, click the button to increase the value of state, and then into the show page to view the status value

5. Submit load

The so-called load (payload) is an additional parameter passed to store.commit.
Index.js under (1) modify the store

    ...
    mutations: {
        increment(state,x) {
            state.count += x
        }
    }
    ...

(2) Modify HelloWorld.vue

......
addCount(){
	this.$store.commit('increment',10)
	console.log(this.$store.state.count)
}
......

6.Action

  • Action similar mutation, except that:
  • Action is submitted mutation, rather than directly change state.
  • Action can contain any asynchronous operation.
    We now use to encapsulate Action INCREMENT
    (. 1) to modify store / index.js, add a actions
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    }

(2) Modify HelloWorld.vue

<template>
    <div>
        show: {{$store.state.count}}
        <button @click="addCount">测试</button>
    </div>
</template>
<script>
export default {
    methods:{
        addCount(){
            this.$store.dispatch('increment')
            console.log(this.$store.state.count)
        }
    }
}
</script>

We use the dispatch call to action, Action also supports load

7. Getter derived properties

Sometimes we need to be derived from the store in the state in some states, for example on the basis of our embodiment the code, we added a property called a remark, if the count value is less than 50 remark property of fuel, not less than 50 less than 100 remark awesome for you, the value is greater than 100 remark that you are the great God. then we need to use getter for us to resolve.
(1) modify the store / index.js, defined increase getters

    getters: {
        remark(state){
            if(state.count<50){
                return '加油'
            }else if( state.count<100){
                return '你真棒'
            }else{
                return '你是大神'
            }
        }
    }

Getter receiving state as its first parameter, can also accept other getter as the second parameter
(2) modify the value of the derived properties displayed HelloWorld.vue

{{$store.getters.remark}}

Here Insert Picture Description

Third, modular

1.Module

Due to the use of a single state tree, the status of all applications will be concentrated in a relatively large objects. When the application becomes very complicated, store the object is likely to become quite bloated.
To solve this problem, Vuex allow us to store is divided into modules (module). Each module has its own state, mutation, action, getter, even nested sub-modules - from top to bottom is divided in the same way the following code to see the model
Here Insert Picture Description
we are now on the project to transform a modular
(1) Modify store / index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


const moduleA ={
     state: {
        count: 0
    },
    mutations: {
        increment(state,x) {
            state.count += x
        }
    },
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    },
    getters: {
        remark(state){
            if(state.count<50){
                return '加油'
            }else if( state.count<100){
                return '你真棒'
            }else{
                return '你是大神'
            }
        }
    }
}
const store = new Vuex.Store({
    modules: {
        a:moduleA
    }
})
export default store   

(2) Review and show.vue HelloWorld.vue

{{$store.state.a.count}}

2. Standard engineering structures

If all states are written in a js, this js must be very bloated, so Vuex suggest you the following code structure to build the project
Here Insert Picture Description
we will follow the above structure, rearrange now less our code:
Create the following (1) store modules folder, create a folder a.js

export default {
     state: {
        count: 0
    },
    mutations: {
        increment(state,x) {
            state.count += x
        }
    },
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    },
}
    
    

Creating getters.js under (2) store

export default {
    remark: state => {
        if(state.a.count<50){
            return '加油'
        }else if( state.a.count<100){
            return '你真棒'
        }else{
            return '你是大神'
        }
    },
    count: state=> state.a.count
}
    

(3) modify the store / index.js

import Vue from 'vue'
import Vuex from 'vuex'
import a from './modules/a'
import getters from './getters'
Vue.use(Vuex)

const store = new Vuex.Store({
    getters,
    modules: {
        a
    }
})
export default store   

(4) modified HelloWorld.vue

<template>
    <div>
        show: {{$store.getters.count}} {{$store.getters.remark}}
        <button @click="addCount">测试</button>
    </div>
</template>
<script>
export default {
    methods:{
        addCount(){
            this.$store.dispatch('increment')
            console.log(this.$store.getters.count)
        }
    }
}
</script>

Guess you like

Origin blog.csdn.net/Eknaij/article/details/96480114