vue之vuex

Posted 鸟随二月

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue之vuex相关的知识,希望对你有一定的参考价值。

vue中data中的数据都加入到响应式系统里了

相关代码

单页面到多页面状态切换

安装

npm install vuex --save

src/store/index.js

src/main.js

在src/store/index.js store中的state加入

  counter: 1000,

在其他组件中引入counter

  <h2>{{$store.state.counter}}</h2>

安装Devtools






切换vuex

devtools和mutations

src/store/index.js store中的mutations加入

src/App.vue


getters

基本使用

src/store/index.js store中的getters加入

  powerCounter(state) {
    return state.counter * state.counter
  }

src/App.vue增加

2.
src/store/index.js store中state中加入

students: [
    {id: 110, name: 'why', age: 18},
    {id: 111, name: 'kobe', age: 24},
    {id: 112, name: 'james', age: 30},
    {id: 113, name: 'curry', age: 10}
  ]

src/store/index.js store中的getters加入

  more20stu(state) {
    return state.students.filter(s => s.age > 20)
  },

src/App.vue增加

 <h2>{{$store.getters.more20stu}}</h2>

传参

src/store/index.js store中的getters加入

  more20stuLength(state, getters) {
    return getters.more20stu.length
  },

src/App.vue增加

 <h2>{{$store.getters.more20stuLength}}</h2>

src/store/index.js store中的getters加入

 moreAgeStu(state) {
    // return function (age) {
    //   return state.students.filter(s => s.age > age)
    // }
    return age => {
      return state.students.filter(s => s.age > age)
    }
  }

src/App.vue增加

   <h2>{{$store.getters.moreAgeStu(12)}}</h2>

mutations

src/store/index.js store中的mutations加入

src/App.vue增加

    <button @click="addCount(5)">+5</button>
    <button @click="addCount(10)">+10</button>
  ......
  methods:{
   addCount(count) {
        // payload: 负载(count这类的名称)
        // 1.普通的提交封装
         this.$store.commit('incrementCount', count)
         //2.
         
  }}

mutation提交风格

src/App.vue增加addCount变为

   addCount(count) {
        // payload: 负载
        // 1.普通的提交封装
        // this.$store.commit('incrementCount', count)

        // 2.特殊的提交封装
        this.$store.commit({
          type: 'incrementCount',
          count
        })
      },

src/store/index.js store中的mutations变为

  incrementCount(state, payload) {
    // console.log(count);
    state.counter += payload.count
  },

payload是

在mutations如此写才能做到响应式,‘address’可以是字符串和number

mutations常量类型

src/store/mutations-types.js

export const INCREMENT = 'increment'

src/store/index.js store中的mutations

import {INCREMENT} from "./mutations-types";
......
 [INCREMENT](state) {
    state.counter++
  },

src/App.vue中methods

   addition() {
        this.$store.commit(INCREMENT)
      },

Actions

当有异步操作时需要用到action
src/store/index.js store中的action中加入

其他组件调用actions时methods加入

升级
src/store/index.js store中的action中加入

aUpdateInfo(context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        context.commit('updateInfo');
        console.log(payload);

        resolve('1111111')
      }, 1000)
    })
  }

其他组件调用actions时methods加入

 updateInfo() {
        // this.$store.commit('updateInfo')
        // this.$store.dispatch('aUpdateInfo', {
        //   message: '我是携带的信息',
        //   success: () => {
        //     console.log('里面已经完成了');
        //   }
        // })
        this.$store
          .dispatch('aUpdateInfo', '我是携带的信息')
          .then(res => {
            console.log('里面完成了提交');
            console.log(res);
          })
      },

modules

src/store/index.js modules加入

// 2.创建对象
const moduleA = {
  state: {
    name: 'zhangsan'
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload
    }
  },
  getters: {
    fullname(state) {
      return state.name + '11111'
    },
    fullname2(state, getters) {
      return getters.fullname + '2222'
    },
    fullname3(state, getters, rootState) {//rooestate是根状态原始state中的变量
      return getters.fullname2 + rootState.counter
    }
  },
  actions: {
    aUpdateName(context) {
      console.log(context);
      setTimeout(() => {
        context.commit('updateName', 'wangwu')//只可以调用自己的
      }, 1000)
    }
  }
}
......
 modules: {
    a: moduleA
  }

src/App.vue

  <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>
   ......
   methods:{
    updateName() {
        this.$store.commit('updateName', 'lisi')
      },
        asyncUpdateName() {
        this.$store.dispatch('aUpdateName')
      }
      }

模块抽离

src/store/index.js

<template>
  <div id="app">
    <h2>----------App内容: 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>

    <h2>----------App内容: info对象的内容是否是响应式----------</h2>
    <h2>{{$store.state.info}}</h2>
    <button @click="updateInfo">修改信息</button>

    <h2>----------App内容----------</h2>
    <h2>{{$store.state.counter}}</h2>
    <button @click="addition">+</button>
    <button @click="subtraction">-</button>
    <button @click="addCount(5)">+5</button>
    <button @click="addCount(10)">+10</button>
    <button @click="addStudent">添加学生</button>

    <h2>----------App内容: getters相关信息----------</h2>
    <h2>{{$store.getters.powerCounter}}</h2>
    <h2>{{$store.getters.more20stu}}</h2>
    <h2>{{$store.getters.more20stuLength}}</h2>
    <h2>{{$store.getters.moreAgeStu(12)}}</h2>

    <h2>----------Hello Vuex内容----------</h2>
    <hello-vuex/>
  </div>
</template>

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

  import {
    INCREMENT
  } from './store/mutations-types'

  export default {
    name: 'App',
    components: {
      HelloVuex
    },
    data() {
      return {
        message: '我是App组件'
      }
    },
    // computed: {
    //   more20stu() {
    //     return this.$store.state.students.filter(s => s.age > 20)
    //   }
    // },
    methods: {
      addition() {
        this.$store.commit(INCREMENT)
      },
      subtraction() {
        this.$store.commit('decrement')
      },
      addCount(count) {
        // payload: 负载
        // 1.普通的提交封装
        // this.$store.commit('incrementCount', count)

        // 2.特殊的提交封装
        this.$store.commit({
          type: 'incrementCount',
          count
        })
      },
      addStudent() {
        const stu = {id: 114, name: 'alan', age: 35}
        this.$store.commit('addStudent', stu)
      },
      updateInfo() {
        // this.$store.commit('updateInfo')
        // this.$store.dispatch('aUpdateInfo', {
        //   message: '我是携带的信息',
        //   success: () => {
        //     console.log('里面已经完成了');
        //   }
        // })
        this.$store
          .dispatch('aUpdateInfo', '我是携带的信息')
          .then(res => {
            console.log('里面完成了提交');
            console.log(res);
          })
      },
      updateName() {
        this.$store.commit('updateName', 'lisi')
      },
      asyncUpdateName() {
        this.$store.dispatch('aUpdateName')
      }
    }
  }
</script>

<style>

</style>

src/store/modules/moduleA.js

export default {
  state: {
    name: 'zhangsan'
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload
    }
  },
  getters: {
    fullname(state) {
      return state.name + '11111'
    },
    fullname2(state, getters) {
      return getters.fullname + '2222'
    },
    fullname3(state, getters, rootState) {
      return getters.fullname2 + rootState.counter
    }
  },
  actions: {
    aUpdateName(context) {
      console.log(context);
      setTimeout(() => {
        context.commit('updateName', 'wangwu')
      }, 1000)
    }
  }
}

src/store/actions.js

export default {
  // context: 上下文
  // aUpdateInfo(context, payload) {
  //   setTimeout(() => {
  //     context.commit('updateInfo')
  //     console.log(payload.message);
  //     payload.success()
  //   }, 1000)
  // },
  aUpdateInfo(context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        context.commit('updateInfo');
        console.log(payload);

        resolve('1111111')
      }, 1000)
    })
  }
}

src/store/getters.js

export default  {
  powerCounter(state) {
    return state.counter * state.counter
  },
  more20stu(state) {
    return state.students.filter(s => s.age > 20)
  },
  more20stuLength(state, getters) {
    return getters.more20stu.length
  },
  moreAgeStu(state) {
    // return function (age) {
    //   return state.students.filter(s => s.age > age)
    // }
    return age => {
      return state.students.filter(s => s.age > age)
    }
  }
}

src/store/mutations.js

import {INCREMENT} from "./mutations-types";

export default {
  // 方法
  [INCREMENT](state) {
    state.counter++
  },
  decrement(state) {
    state.counter--
  },
  incrementCount(state, payload) {
    // console.log(count);
    state.counter += payload.count
  },
  addStudent(state, stu) {
    state以上是关于vue之vuex的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段13——Vue的状态大管家

vue-cli之vuex

vue-cli+webpack+router+vuex---之vuex使用

VUE学习笔记:28.脚手架vue-cli之vuex

vue之vuex

vue之vuex