Learn to understand guide Vuex strengthening state management model

file

1

Vuex What is it? It is the state management of Vue, in the use of vue, vue need to pass values ​​between the various components is very painful, in vue, we can use vuex to save state values ​​we need to manage, once the value is changed, All references to places that value will be automatically updated. It is not very convenient, easy to use it?

vuex is designed specifically for vue.js state management, centralized storage management application and the status of all components, vuex also integrated vue official transfer tool, a core application is vuex store, a container, store contains most of the state application.

Then we apply vuex it at what time? vuex is not used lightly, small, simple applications is not so appropriate, because with the Vuex cumbersome redundant, more suitable to use simple store mode; for vuex more suitable for medium and large single-page application: for use in multiple views the same state, different views of the same state needs to be changed.

The method of parameter passing for nested components, it is very cumbersome, and the inability to transfer state between brothers assembly; Sons assembly using a direct reference or multiple copies and to change state by the synchronization event, usually results not maintainable code.

npm install vuex --save //yarn add vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

Vue introduced in place to create vuex instance, vuex

import Vue from 'vue'//引入vue
import Vuex from 'vuex'//引入vuex

Vue.use(Vuex); //使用 vuex

import store from './store' //引入状态管理 store

Vuex.Store a new instance, and register state, mutations, actions, getters to Vuex.Store example:

import Vue from 'vue';
import Vuex from 'vuex'; // 引入vuex
import store from './store' // 注册store

Vue.use(Vuex); // 使用vuex

export default new Vuex.Store({
 state: {...},
 mutations: {...},
 actions: {...},
 getters: {...}
})

// 当代码量大额时候写个js文件即可
store
action.js
index.js
mutation.js
// 引入到store/index.js注册到vuex实例中
import mutations from './mutations' // 引入mutations
import actions from './action' // 引入action
import Vue from 'vue' // 引入vue
import Vuex from 'vuex' // 引入vuex

Vue.use(Vuex);
// 创建state
const state = {
 count: 0
};

export default new Vuex.Store({
 state, // 注册state
 action, // 注册actions
 mutations // 注册mutations
})

After creating vuex.store, you need to introduce in the entry file main.js in store and register to vue example, so that you can use at any store components.

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' // 引入状态管理store

Vue.config.productiontip = false
new Vue({
 router,
 store, // 注册store
 render: h => h(App)
}).$mount('#app')

Used in the assembly, each property incorporated vuex the corresponding auxiliary function:

import {mapActions, mapState,mapGetters} from 'vuex' 
//注册 action 、 state 、getter

2

Vue create a project, enter vue int webpack web, installation vuex, command: npm install vuex --save.

store,index.js

import Vue from 'vue' // 引入vue
import Vuex from 'vuex' // 引入vuex
// 使用vuex
Vue.use(Vuex);
// 创建Vuex实例
const store = new Vuex.store({
})
export default store // 导出store

main.js

import Vue from 'Vue'
import App from './App'
import router from './router'
import store from '.store'

Vue.config.productiontip = false

new Vue({
 el: '#app',
 store,
 router,
 components: {App},
 ...
})

State, we can get data defined in the page through this $ store.state.:

import Vue from 'vue' // 引入vue
import Vuex from 'vuex' // 引入vuex
// 使用vuex
Vue.use(Vuex);

// 创建Vuex实例:
const store = new Vuex.Store({
 state: {
  count: 1
 }
})
export default store // 导出store
{{this.$store.state.count}}

Getters equivalent vue computed in calculating properties, getters return value based on its dependencies are cached, and only when it is dependent on the value changes will be recalculated.

Getters can be used to monitor changes in the state value, calculated results returned.

{{this.$store.getSateCount}}
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
 state: {
  count: 1;
 },
 getters: {
  getStateCount: function(state){
   return state.count+1;
  }
 }

Mutations

{{this.$store.state.count}}
<button @click="addFun">+</button>
<button @click="reductionFun">-</button>

methods: {
 addFun() {
  this.$store.commit("add");
 },
 reductionFun() {
  this.$store.commit("reduction");
 }
}

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// 创建Vuex实例
const store = new Vuex.store({
 state: {
  count: 1
 },
 getters: {
  getStateCount: function(state){
   return state count+1;
  }
 },
 mutations: {
  add(state) {
   state.count = state.count+1;
  },
  reduction(state){
   state.count = state.count-1;
  }
 }
})
export default store // 导出store

Actions:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
 state: {
  count: 1;
 },
 getters: {
  getStateCount: function(state){
   return state.count+1;
  }
 }
 mutations: {
  add(state) {
   state.count = state.count+1;
  },
  reduction(state) {
   state.count = state.count-1;
  }
 },
 actions: {
  addFun(context) {
   context.commit("add");
  },
  reductionFun(context) {
   context.commit("reduction");
  }
 }
// vue
methods: {
 addFun() {
  this.$store.dispatch("addFun");
  // this.$store.commit("add");
 },
 reductionFun() {
  this.$store.dispatch("reductionFun");
 }
}

By value:

methods: {
 addFun() {
  this.$store.dispatch("addFun");
  // this.$store.commit("add");
 },
 reductionFun() {
  var n = 10;
  this.$store.dispatch("reductionFun", n);
 }
}
 mutations: {
  add(state) {
   state.count = state.count+1;
  },
  reduction(state,n) {
   state.count = state.count-n;
  }
 },
 actions: {
  addFun(context) {
   context.commit("add");
  },
  reductionFun(context,n) {
   context.commit("reduction",n);
  }
 }

mapState、mapGetters、mapActions

this.$stroe.state.count
this.$store.dispatch('funName')
<div style="border:1px solid red; margin-top: 50px;">
 {{count1}}
</div>

import {mapState,mapActions,mapGetters} from 'vuex';

computed: {
 ...mapState({
  count1:state=> state.count
 })
}

3

The initial state is the bottom data, property getters equivalent calculation of vue, the data is processed and extended state, and when the need to modify mutations state, defined mutations, Actions when needed to process a lot of mutations when, for distribution of the mutations, asynchronous processing is herein defined actions.

When a vuex vue.js developed for application state management mode, it uses the status of all components centralized storage management application, and to ensure that the appropriate rules in a predictable manner changed.

So what kind of state management model is written in the format:

new Vue({
 // state 初始状态(数据)
 data() {
  return {
   count: 0
  }
 },
 template: `<div>{{count}}</div>`,
 methods: {
  increment() {
   this.count++
  }
 }
})

Multiple arrays sharing status:

Multiple views of the same depends on the state and behavior from different views of the same state needs to be changed.

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {  //状态
    count: 0
  },
  mutations: {  //变化
    increment (state) {
      state.count++
    }
  }
})
store.commit('increment')

state the initial state, getter equivalent to the calculated property, mutation status change, action action, module module.

Vue.use(Vuex)

const app = new Vue({
  el: '#app',
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}
computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

getter return value based on its dependencies are cached, and only when it is dependent on the value has changed will be recalculated.

const store = new Vuex.Store({

  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todos.done)
    }
  }
  
})
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

store.getters.doneTodosCount // -> 1

mapGetters helper function is to store the property getter mapped to a local computing

The only way to change Vuex the store in the state is to submit a mutation

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

store.commit('increment', 10)

this. $ store.commit ( 'xxx') submitted mutation

mapMutations auxiliary function assembly methods mapped to store.commit call

import { mapMutations } from 'vuex'
export default {
  methods: {
  
    ...mapMutations([
      'increment',
      // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
      // `mapMutations` 也支持载荷:
      'incrementBy' 
      // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    
  this.incrementBy(); 调用
  
    ...mapMutations({
      add: 'increment' 
      // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
    
  }

}

Action submitted mutation is a change, rather than directly change state. Action can contain any asynchronous operation.

store.dispatch('increment')

The methods use mapActions helper component mapped to store.dispatch call

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
  
    ...mapActions([
      'increment', 
      // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' 
      // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    
    ...mapActions({
      add: 'increment' 
      // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

view

CLI-mounted VUE
CNPM the install -g-CLI VUE

Installation webpack template:
VUE myProject the init webpack

Installation depends
cnpm install

Installation routing
cnpm install vue-router --save-dev

安装 axios http
cnpm install axios --save

4

vue global objects and simple difference:

vuex responsive state, the only way to change the state of the store is submitted explicitly commit, mutation during storage.

The core Vuex that store, store contains most of the state (state) applications.

One of the easiest store contains state and mutation, the state of the object can be obtained by store.state, and trigger state changes by store.commit method.

State, stores all the basic "global objects" application, this. $ Store.state.XXX can be accessed.
mapState: Use this helper to help us generate calculate property, obtaining a plurality of state values.

Getter derived from the store in the state in some state, receiving state as the first parameter, the second parameter may be calculated by value, it will be exposed as store.getters objects can be accessed in the form of attribute values.

Vuex the mutation, each mutation, event type (type) and a callback function (handler)

Action is submitted mutation, not directly change the state, can contain any asynchronous operation, triggered by store.dispatch method.

5

vuex what appears to solve the problem? We know that the scope between components are independent communications components and subcomponents of a parent can be mass participation by prop property, but communication between the brothers components is not so friendly.

First to tell their parent components, and then tell the other components by a parent component, once a lot of time components, it is not convenient communication, vuex solve this problem, so you can easily communicate between multiple sub-assemblies.

|-store/ // 存放vuex代码
| |-actions.js
| |-getters.js
| |-index.js
| |-mutations.js
| |-state.js
|-store/ // 存放vuex代码
| |-Module1
| | |-actions.js
| | |-getters.js
| | |-index.js
| | |-mutations.js
| | |-state.js
| |-Module2
| | |-actions.js
| | |-getters.js
| | |-index.js
| | |-mutations.js
| | |-state.js
| |-index.js // vuex的核心,创建一个store

What vuex that?

Vuex is a specially developed for the application state management vue.js, it is the use status of all components centralized storage management application, and a corresponding state rules to ensure a predictable manner changed. Vuex Vue is also integrated into the official transfer tool devtools extension, provides a time-travel, such as zero-configuration debugging, a snapshot of the state of import and export and other advanced debugging features.

What is the "state management"?

new Vue({

  // state
  data () {
    return {
      count: 0
    }
  },
  
  // view
  template: `
    <div>{{ count }}</div>
  `,
  
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
  
})

state, the driving source of the application data;
view, declaratively mapped to the view state;
Actions, in response to user input on the view state variations.

file

Our application encountered a number of components shared state, the simplicity of one-way data flow can easily be destroyed:

It relies on the same state of the plurality of views.
Behavior needs to be changed from the different views of the same state.

file

Core concepts: State, Getter, Action, Module

Vuex and simple global objects have a different following two points:

1.Vuex state is responsive to storage.
2. not directly change the state of the store.

Creating a store

// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)

const store = new Vuex.Store({

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

To get the state of the object by store.state, triggered by the state store.commit method change

store.commit('increment')

console.log(store.state.count) // -> 1

With an object contains all of the application level state, each application will contain only a store instance. Single state tree. Vuex state memory is responsive to read status methods, i.e., it is returned in the attribute calculation.

// 创建一个 Counter 组件

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return store.state.count
    }
  }
}

Vuex by store options

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})


const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

Use mapState helpers help us generate calculate property

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}


computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
]

mapState 函数返回的是一个对象。

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}

We need to derive some state from store in the state in

computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

getter return value based on its dependencies are cached, and only when it is dependent on the value has changed will be recalculated.

const store = new Vuex.Store({

  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
  
})

Getter will be exposed as an object store.getters

store.getters.doneTodos 

// -> [{ id: 1, text: '...', done: true }]

Getter can also accept other getter as the second argument:

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

store.getters.doneTodosCount // -> 

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

store.getters.getTodoById(2) 
// -> { id: 2, text: '...', done: false }

mapGetters helper function is mapped to a local store the calculated getter properties:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

The only way to Vuex the store in the state is to submit a mutation

Each event type (type) mutation have a string and a callback function (handler)

Additional parameters passed to store.commit, namely mutation load (payload):

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

store.commit('increment', 10)

In most cases, the load should be an object

It may comprise a plurality of fields and records mutation

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

store.commit('increment', {
  amount: 10
})

store.commit({
  type: 'increment',
  amount: 10
}

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

Action

Simple action:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
}

store.dispatch('increment')

store.dispatch can handle the returned Promise action handler triggered

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
store.dispatch('actionA').then(() => {
  // ...
}

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

file:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
store.js 文件:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    num: 1
  },
  mutations: {
    changeFunction (state, num) {
      state.num++
    }
  }
})

main.js 文件:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

views/demo.vue 文件:

<template>
  <div>
    <p>{{msg}}</p>
    <button @click="getNum">getNum</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      msg: '0'
    }
  },
  methods: {
    getNum () {
      this.msg = this.$store.state.num
    }
  }
}
</script>

Want to get vuex in the global data, it can be seen as a class vue

file

file

file

file

file

file

Modular:

const moduleA = {
  namespaced: true,
  state: {
    name: ''
  },
  getters: {},
  mutations: {},
  actions: {}
}
export default moduleA;
const moduleB = {
  namespaced: true,
  state: {
    name: ''
  },
  getters: {},
  mutations: {},
  actions: {}
}
export default moduleB;
import moduleA from './moduleA.js';
import moduleB from './moduleB.js';
const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
export default store;
this.$store.state.a.name // -> moduleA 的状态name
this.$store.state.b.name // -> moduleB 的状态name
computed: {
    ...mapState('a', {
      name: state => state.name
    }),
    ...mapState('b', {
      name: state => state.name
    })
}

file

file

state示例

const state = {
  name: 'weish',
  age: 22
};
 
export default state;
getters.js 示例

export const name = (state) => {
  return state.name;
}
 
export const age = (state) => {
  return state.age
}
 
export const other = (state) => {
  return `My name is ${state.name}, I am ${state.age}.`;
}

Refer to the official document: https: //vuex.vuejs.org/

On the current content of the article that is involved in front-end, PHP knowledge, if you are interested to follow, very honored, can you find really identify what the British! Also thank you for your attention in the coming days, hoping been quietly supporting me, I will try to write more good works. We grow together, learn from the zero-based programming, the user-friendly front-end Web presentation areas, data structures and algorithms, network theory, etc. to the junior partner. Share Web front-end related technical articles, tools, resources, course selection, hot information.


If this number of local contents do not get bits (for example: to copyright or other problems), please contact us for rectification can be timely and will be processed in the first time.


Please thumbs up! Because you agree / encouragement is the greatest power of my writing!

Welcome attention to Dada 's CSDN!

This is a quality, attitude blog

7d927f18ebd05ea1d505a572393fbc87.jpg

Guess you like

Origin www.cnblogs.com/dashucoding/p/11909215.html