vue记录---vuex的使用

七、vuex的使用

1)安装
cnpm i vuex -S
2)配置
// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

// 使用组件
Vue.use(Vuex)

export default new Vuex.Store({
  // 存放状态(数据)
  state: {
    num: 1
  },
  getters: {},
  // 修改state数据
  mutations: {},
  // 处理异步请求
  actions: {}
})

3)注册
// src/main.js
import Vue from 'vue'
import App from './App.vue'

// 引入配置好的vuex
import store from '@/store';

Vue.config.productionTip = false

let a = 10;

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

4)使用
  • 在组件中获取state数据以及派发、提交其action、mutation
    <template>
      <div>
        <h1>计数器</h1>
        <h2>当前vuex中的num为:{{ num }}</h2>
        <h2>增量:<input type="number" v-model="value"></h2>
        <button @click="increment">增加</button><button @click="incrementAsync">异步增加</button>
      </div>
    </template>
    
    <script>
    import { mapState } from 'vuex';
    
    export default {
      name: "App",
      data() {
        return {
          value: 1
        }
      },
      computed: {
        // 映射vuex中的num给当前组件计算属性的num
        ...mapState({
          num: state => state.num
        })
      },
      methods: {
        increment() {
          // 提交mutation
          this.$store.commit("INCREMENT", this.value)
        },
        incrementAsync() {
          // 派发action
          // this.$store.dispatch("incrementAsync", this.value)
          
          // action中返回promise时可进行then、catch操作
          this.$store.dispatch("incrementAsync", this.value).then((data) => {
            console.log(data)
          }).catch((err) => {
            console.log(err)
          });
        }
      },
    };
    </script>
    
    <style>
    </style>
    
    
  • 其中vuex中的配置如下:
    
    import Vue from 'vue';
    import Vuex from 'vuex';
    
    // 使用组件
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      // 存放状态(数据)
      state: {
        num: 1
      },
      getters: {},
      // 修改state数据
      mutations: {
        INCREMENT(state, payload) {
          state.num += payload * 1
        }
      },
      // 处理异步请求
      actions: {
        incrementAsync({ commit }, payload) {
          // 异步操作模拟发送请求
          // setTimeout(() => {
          //   commit("INCREMENT", payload)
          // }, 1000)
          
          // 也可返回promise进行其他操作
          return new Promise((resolve, reject) => {
            try {
              setTimeout(() => {
                commit("INCREMENT", payload)
                resolve("成功")
              }, 1000)
            } catch (error) {
              reject(error)
            }
          })
        }
      }
    })
    
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 😆 OK!本节我们来学习使用Actions,Actions存在的意义是vuex作者假设你在修改state的时候有异...
    木头就是我呀阅读 24,539评论 5 21
  • vuex 状态管理器 作为应用中所有组件的中央储存 只能以预定的方式去操作状态 把所有组件共享的状态抽取出来作为全...
    一只大椰子阅读 802评论 0 1
  • 🤗 OK!首先恭喜你看到了这里,前面我们实现了从盘古开天辟地开始......咳咳,其实我们从初始化vue项目,到安...
    木头就是我呀阅读 951评论 0 0
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,964评论 0 7
  • ##模块化开发 浏览器只支持`ES6`的模块化,其他的需要使用`webpack`处理后才能在浏览器上使用 模块化是...
    Hachim阅读 411评论 0 0