zoukankan      html  css  js  c++  java
  • vuex笔记

    1、npm install vuex //安装至生产环境

    2、在src中新建vuex文件夹,添加store.js文件,在store.js文件中

    a、引入vue,vuex:

    import Vue from 'vue'

    import Vuex from 'vuex'

    Vue.use(Vuex)

    b、声明全局共享状态及数据:

    const state = {

      num:1

    }

    c、声明用于修改全局state对象属性的mutation对象,并添加方法:

    const mutations = {

      add(state,n) {//第一个参数为固定参数指向全局state对象,第二个参数为自定义参数

        return state.num += n

      },

      reduce(state) {

        return state.num --

      }

    }

    d、声明用于监听state对象内属性变化的并作出修改的getters对象

    const getters = {

      num(state){//每当state中的num属性变化时都会调用该num方法

        return state.num += 3

      }

    }

    e、声明异步修改状态的actions,actions可以调用mutations内的方法,作用与mutations类似,只不过是异步的去修改state,不阻塞js执行流

    const actions = {

      addAction(context){//context是整个store对象

        context.commit('add',10) //直接调用mutation中的add方法

      },

      reduceAction({commit}){//可以直接使用commit作为参数,注意{}

        commit('reduce')

      }

    }

    3、在store.js中对外开放以上定义的对象

    export default new Vuex.Store({

      state,mutations,getters,actions

    })

    4、在需要使用的组件文件中引入vuex,在此组件中模板中可以通过$store拿到store实例,js用this.$store

    import store from '@/vuex/store'

    import { mapState,mapMutation,mapGetters,mapActions }

    export default {

      data(){

        return {}

      },

      computed:{

        ...mapState(['num']),//直接引入store中的num在此组件中可以直接使用

        ...mapGetters(['num']) //直接引入store中的num在此组件中可以直接使用,每当num有变化时都会改变

      },

      methods:{

        ...mapMutations(['add',reduce]),//在数组中引入mutations内你所需的方法,在此组件中你就可以直接调用了

        ...mapActions(['addAction']),//同上

      }

    }

    5、模块化

    const moduleA = {

      state:{},

      mutaions:{}

    }

    const moduleB = {

      state:{},

      mutaions:{}

    }

    export default new Vuex.store({

      modules:{a:moduleA,b:moduleB}

    })

  • 相关阅读:
    c++函数模板
    C++左移运算符重载
    and or bool and a or b 原理解释
    Python的垃圾回收机制
    《C++ 101条建议》学习笔记——第一章快速入门
    在应用中嵌入Python:转
    使用C++扩展Python的功能 转自:http://blog.csdn.net/magictong/article/details/8897568#comments
    python扩展实现方法--python与c混和编程 转自:http://www.cnblogs.com/btchenguang/archive/2012/09/04/2670849.html
    python文件头的#-*- coding: utf-8 -*- 的作用
    Pythhon 字典 key in dict 比 dict.has_key (key)效率高 为什么?
  • 原文地址:https://www.cnblogs.com/muzs/p/10534194.html
Copyright © 2011-2022 走看看