基于vue-cli的vue项目之vuex的使用(commit参数)

1.安装 npm install vuex 

2.在src目录下新建一个store目录,然后在store目录下新建一个js,在js里面引用一下vuex,代码如下:

import Vue from 'vue';  

import Vuex from 'vuex';  

Vue.use(Vuex);  

export default store = new Vuex.Store({  //注意:这里的store的s必须大写

state:{

这里写一些申明的数据之类的,例如:

list: [

{id:1,name:'鱼香肉丝',price:12,count:0,gw:true},

{id:2,name:'鱼香肉丝',price:12,count:0,gw:true},

{id:3,name:'鱼香肉丝',price:12,count:0,gw:true},

{id:4,name:'鱼香肉丝',price:12,count:0,gw:true}

],

},

mutations:{

这里写一些方法,例如:

push (state, index) {

state.list[index].count++

state.list[index].gw =false

  state.list1.push(state.list[index])

},

}

})

3.在.main.js使用vuex并关联store

import Vue from 'vue'  

import App from './App'  

import router from './router'  

import store from './vuex/store';  //使用store

Vue.config.productionTip = false;  

new Vue({  

    el: '#app',  

    router,  

    store,  //关联store

template: '',  

    components: {  

        App  

    },  

})  

4.在组件中使用vuex,并调用vuex/store.js的方法,例如:

 export default {  

        name: 'app',  

        computed: {

       // 数据

         list () {

            return this.$store.state.list

       }

}

        methods: {  

         push (index) {

           this.$store.commit('push', index)

          },

        }

    }  

这是我本人的理解,希望可以给你们一些帮助,vuex里面还有很多方法,可以到官网去进一步的了解与学习。

你可能感兴趣的:(基于vue-cli的vue项目之vuex的使用(commit参数))