51. Vuex for Vue

table of Contents

1. What is Vuex

Second, install the Google plug-in

Three, the basic use of Vuex

Fourth, the core concept of Vuex

5. Project structure


git :https://gitee.com/cxy-xupeng/vue-vuex.git

1. What is Vuex

Vuex is a state management tool. When a component is called by multiple other components, and what the state of this component is, this needs to be managed (a bit concurrency), vuex is used to manage this state, and it can be responsive .

 

Second, install the Google plug-in

Let me talk about the ideal steps first:

1. Click on the three dots in the upper right corner of Google Chrome: (No, no, no one really uses Google Chrome? If not, you can use Firefox)

2. Select "More Tools", select "Extensions"

3. Click "Extensions" in the upper left corner

4. Click on the lower left corner to open the Chrome Web Store. Then if you can open it, find Vue.js devtools to download it (of course I didn’t open it...)

 

I would like to call it: the emperor's shop. Because it can't be opened at all.

The following explains how I installed it:

1. Baidu search: minimalist Google plug-in

2. Download the vue plugin

3. After downloading, it is a compressed package, decompress this compressed package

4. Open Google Chrome, three dots in the upper right corner, select "More Tools", select "Extensions". Just drag the CRX file from our previous step into the browser on this page. Just install it

 

 

Three, the basic use of Vuex

1. Create a project

Do you need a router here? Everyone can choose N

We modify the homepage appropriately, delete helloworld, and then delete the router in main.js, and check the result:

2. Install vuex

npm install vuex --save

3. Table of Contents

4. The vuex plug-in is written in index.js, where state represents the global state and mutations represents the method

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

//1.安装插件
Vue.use(Vuex)

//2.创建对象
const store = new Vuex.Store({
  state:{//状态
    count:1000
  },
  mutations:{//方法
    increment(state){
      state.count++;
    },
    decrement(state){
      state.count--;
    },
  },
  actions:{

  },
  getters:{

  },
  modules:{

  }

})

//3.导出store对象
export default store

5. The HelloVuex.vue method of passing from parent to child uses attributes, but the parent also uses the global state

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

<script>
  export default{
    name:'HelloVuex',
    props:{
      count:Number
    }
  }
</script>

<style>
</style>

6.main.js: Introduce store

import Vue from 'vue'
import App from './App'
import store from './store/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

7.App.vue: the method of using attributes

<template>
  <div id="app">
    <h2>{
   
   {message}}</h2>
    <h2>{
   
   {counter}}</h2>
    <h2>{
   
   {$store.state.count}}</h2>
    <button @click="addition">+</button>
    <button @click="substraction">-</button>
    <hello-vuex :count="counter"></hello-vuex>
  </div>
</template>

<script>
  import HelloVuex from './components/HelloVuex.vue'

export default {
  name: 'App',
  data(){
    return{
      message:'徐鹏',
      counter:0

    }
  },
  components:{
    HelloVuex
  },
  methods:{
    addition(){
      this.$store.commit('increment')
    },
    substraction(){
      this.$store.commit('decrement')
    }
  }
}
</script>

<style>
</style>

8. View the results: 

 

Fourth, the core concept of Vuex

1.State

  • Single state tree: Create only one object, not multiple objects created by our vuex plugin
  • The data placed in the state at the beginning will be monitored in response. When the attribute changes, all pages that use the attribute will be notified. But undefined attributes will not be responsive

2.Getters

  • If there are calculations for the attribute value, put it here for processing

3.Mutation

  1. The only way to update vue's store status: submit Mutation
  2. Mutation mainly includes two parts: string event type (type) + callback function (handler) (the first parameter is state)
  3. Mutation update: need to commit
  4. Submit by type: In the store, the parameter is the payload, where the payload contains the parameters you need
  5. If you want the properties that are not defined in the state to be responsive, the Vue.set() method can be used to add properties. Vue.delete() delete attribute
  6. The method names in index.js and App.vue are actually the same, we can extract constants
  7. The method in Mutation must be a synchronous method, otherwise devtools will not track it well

4.Action

  1. Because Mutation does not use asynchronous methods, for asynchronous methods, we use in action

5.Module

  1. Because state uses a single state tree, but it will be bloated later. Therefore, the store can be divided into multiple modules

 

Fourth, the structure of the object

//对象的结构
const obj = {
  name:'aa',
  age:11,
  height:1.8
}

const {name,age} = obj

 

Five, examples of vuex

HelloVuex.vue

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

<script>
  export default{
    name:'HelloVuex',
    props:{
      count:Number
    }
  }
</script>

<style>
</style>

mutationstype.js

export const INCREMENT = 'increment'

main.js

import Vue from 'vue'
import App from './App'
import store from './store/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

View app

<template>
  <div id="app">
    <h2>{
   
   {message}}</h2>
    <h2>{
   
   {counter}}</h2>
    <h2>HelloVuex的值:<hello-vuex :count="counter"></hello-vuex></h2>

    <h2>-----------vuex的state----------------</h2>
    <h2>{
   
   {$store.state.count}}</h2>

    <h2>-----------vuex的getters----------------</h2>
    <h2>count的平方:{
   
   {$store.getters.powerCounter}}</h2>
    <h2>年龄大于等于20的学生:{
   
   {$store.getters.more20stu}}</h2>
    <h2>年龄大于等于20的学生数量:{
   
   {$store.getters.more20stucount}}</h2>
    <h2>年龄大于指定数字的学生:{
   
   {$store.getters.moreAgeStu(5)}}</h2>


    <h2>-----------vuex的mutations----------------</h2>
    <button @click="addition">+</button>
    <button @click="substraction">-</button>
    <button @click="addCount(5)">+5</button>
    <button @click="addCount(10)">+10</button>
    <button @click="addStudent">添加学生</button>
    <button @click="updateStudent">响应式修改学生</button>


    <h2>-----------vuex的modules----------------</h2>
    <h2>{
   
   {$store.state.a.name}}</h2>
    <button @click="updateName">修改名字</button>
    <h2>{
   
   {$store.getters.fullname}}</h2>
    <h2>{
   
   {$store.getters.fullname2}}</h2>
    <h2>{
   
   {$store.getters.fullname3}}</h2>
    <button @click="asyncUpdateName">异步修改名字</button>



  </div>
</template>

<script>
  import HelloVuex from './components/HelloVuex.vue'
  import {INCREMENT} from './store/mutationstype.js'

export default {
  name: 'App',
  data(){
    return{
      message:'徐鹏',
      counter:0

    }
  },
  components:{
    HelloVuex
  },
  methods:{
    //1.普通提交封装
    addition(){
      this.$store.commit(INCREMENT)
    },
    substraction(){
      this.$store.commit('decrement')
    },
    // addCount(count){
    //   this.$store.commit('incrementCount',count)
    // },
    //2.特殊的提交封装
    addCount(count){
      this.$store.commit({
        type:'incrementCount',
        count
      })
    },
    addStudent(){
      const stu = {id:4,name:'ddd',age:40}
      this.$store.commit('addStudent',stu)
    },
    updateStudent(){
      // this.$store.commit('updateStudent')
      this.$store.dispatch('aUpdateStudent','我是payload')
    },
    updateName(){
      this.$store.commit('updateName','李四')
    },
    asyncUpdateName(){
      this.$store.dispatch('aaUpdateStudent')
    }
  }
}
</script>

<style>
</style>

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import {INCREMENT} from './mutationstype.js'

//1.安装插件
Vue.use(Vuex)

//2.创建对象
const moduleA = {
  state:{
    name:'张三'
  },
  mutations:{
    updateName(state,payload){
      state.name = payload
    }
  },
  actions:{
    aaUpdateStudent(context){
      console.log(context.rootGetters)
      setTimeout(()=>{
        context.commit('updateName','王五')
      },1000)
    }
  },
  getters:{
    fullname(state){
      return state.name+'111'
    },
    fullname2(state,getters){
      return getters.fullname+'222'
    },
    fullname3(state,getters,rootState){
      return getters.fullname2+rootState.count
    }
  }
}


const store = new Vuex.Store({
  state:{//状态
    count:1000,
    students:[
      {id:1,name:'aaa',age:10},
      {id:2,name:'bbb',age:20},
      {id:3,name:'ccc',age:30},
    ]

  },
  mutations:{//方法
    [INCREMENT](state){
      state.count++;
    },
    decrement(state){
      state.count--;
    },
    //type提交风格
    incrementCount(state,payload){
      state.count += payload.count;
    },
    addStudent(state,stu){
      state.students.push(stu)
    },
    updateStudent(state){
      //响应式增加state里面没有的属性
      Vue.set(state.students[0],'address','上海')
      //响应式删除state的属性
      Vue.delete(state.students[1],'name')
    }
  },
  actions:{
    //context:上下文
    aUpdateStudent(context,payload){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          context.commit('updateStudent')
          console.log(context)
          resolve('111')
        },1000)
      }).then(res=>{
        console.log('完成提交')
        console.log(res)
      })
    }

  },
  getters:{//变化状态的值
    powerCounter(state){
      return state.count * state.count
    },
    more20stu(state){
      return state.students.filter(s=>s.age>=20)
    },
    more20stucount(state,getters){
      return getters.more20stu.length
    },
    //自己传参
    moreAgeStu(state){
      return function(age){
        return state.students.filter(s=>s.age>=age)
      }
    }
  },
  modules:{//模块
    a:moduleA,
    b:{
      state:{},
      mutations:{},
      actions:{},
      getters:{}
    },

  }

})

//3.导出store对象
export default store

 

5. Project structure

We are before, all the code is written in one file, too messy, it needs a reasonable structure:

We took out all the previous ones.

The specific code can be viewed by yourself through git

Guess you like

Origin blog.csdn.net/qq_40594696/article/details/111151464