vuex基础用法

简单汇总一下vuex的最基础的用法

store.js
创建vuex对象

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    updateCount (state, num) {
      state.count = num
    }
  }
})
export default store


index.js
在入口文件引入store.js
import store from './store/store'
new Vue({
  router,
  store,
  render: (h) => h(App)
}).$mount('#root');

app.vue

{{count }}

export default{ computed: { count () { return this.$store.state.count//调用store中的state的值 } }, mounted () { console.log(this.$store) let i = 1; setInterval(() => { this.$store.commit('updateCount',i++)//调用store的mutations },1000) } }

服务端渲染的写法(推荐使用)

store.js

import Vuex from 'vuex'

export default () => {
  return new Vuex.Store({//返回一个vuex对象,防止vuex对象溢出
    state: {
      count: 0
    },
    mutations: {
      updateCount (state, num) {
        state.count = num
      }
    }
  })
}

index.js(入口文件)

import Vuex from 'vuex'
import createStore from './store/store'
Vue.use(Vuex)
const store = createStore()
new Vue({
  router,
  store,
  render: (h) => h(App)
}).$mount('#root');

app.vue

{{count }}

export default{ computed: { count () { return this.$store.state.count//调用store中的state的值 } }, mounted () { console.log(this.$store) let i = 1; setInterval(() => { this.$store.commit('updateCount',i++)//调用store的mutations },1000) } }

你可能感兴趣的:(vuex基础用法)