美文网首页
vueX的使用

vueX的使用

作者: 大笑一声 | 来源:发表于2018-09-05 15:30 被阅读0次

    第一步:下载cnpm install vuex --save

    第二步:在src目录下创建store目录,在store目录中创建三个文件

     ①state.js://保存数据状态

        let state={

            count:0,

         goodsList:[]

       }

          export default state;

    ②mutations.js://写一下操作数据状态的方法

      import state from './state.js'//导入数据状态state

      export default{

      increment(state,num){//increment加方法

       state.count+=num;

      },

    reduce(state,num){//reduce减方法

    state.count-=num;

    },

      addgoods(state,obj){//添加数组的方法

       state.goodsList.push(obj)

     }

     }

    ③index.js:把state文件、mutations文件、getters文件集合到一起方便导出

            import state from './state';

            import mutations from './mutations'

            import getters from './getters'

            export default{

            state,

            mutations,

            getters

    }

    ④getters.js:相当于computed计算属性,把需要在页面显示的数据配置一下

            export default{

                count:(state)=>{

                return state.count;

            }

        }

    第三步:在min.js中配置

    import  Vuex  from  'vuex';

    Vue.use(Vuex);

    import storeObj from '@/store/index'//导出引入全局vueX

    let store=new Vuex.Store(storeObj);//使用

    new Vue({

            el:'#app',

            router,

            store,//在new Vue中注册全局使用

    })

    第四步:创建vue组件

    比如:com11.vue组件

    <button @click='red()'>减少3</button>

    script中使用方法:

    import{//先引入vuex 中mutations方法

      mapMutations

    }  from 'vuex'

        export default {

          name:"com11",

          methods:{

              ...mapMutations([

                    'reduce'//使用vuemutations中的减法方法

                ]),

         red(){//减法方法

           this.reduce(3)

          }

          }

    }

    比如:com22.vue组件(显示count)

    com3

    显示{{count}}

       import {

       mapGetters

    }from 'vuex'

      export default {

     name:"com33",

    computed:{

    ...mapGetters([

       'count'

          ])

    }

    }

    相关文章

      网友评论

          本文标题:vueX的使用

          本文链接:https://www.haomeiwen.com/subject/nopawftx.html