vuex入门---周肥肥建

1.安装vuex插件

npm install vuex --save

2.加载vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

3.创建一个store(内带两个参数,两个方法)

const store = new Vuex.Store({
  state: {
    count: 0,
    student:[{id:0,name:'zhu1',age:19,sex:'boy'},
      {id:1,name:'zhu1',age:19,sex:'boy'},
      {id:2,name:'zhu1',age:19,sex:'boy'},]
  },
  mutations: {
    add (state) {
      state.count++
    },
    sub (state) {
      state.count--
    }
  }

4.导出store

export default  store;

5.在main.js中加载store

import store from "./store/index.js";

6.在 new vue方法中加入加载的store如:

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

7.在组件中调用;案例


    

{{$store.state.count}}

{{this.$store.state.student[0].name}}

你可能感兴趣的:(vue)