Vuex 的使用方式(初级版)

2018-12-24  本文已影响23人  阿畅_
  1. Vue 模板 render 数据 (state)
  2. components 接受用户的交互,触发 actions ,通过 dispatch 触发
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  count: 1
}

const mutations = {
  increment (state) {
    state.count += 1
  },
  decrement (state) {
    state.count -= 1
  }
}

const actions = {
  increment: ({commit}) => {
    commit('increment')
  },
  decrement: ({commit}) => {
    commit('decrement')
  }
}
const store = new Vuex.Store({
  state,
  mutations,
  actions
})
new Vue({
  el: '#app',
  render (h) {
    return h(App)
  },
  store
})

  <template>
  <div id="app">
    <img src="./assets/logo.png">
    <div>{{ $store.state.count }}</div>
    <button @click="increment">增加</button>
    <button @click="decrement">减少</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'App',
  data () {
    return {
      msg: 'hello world'
    }
  },
  methods: mapActions([
    'increment',
    'decrement'
  ])
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

上一篇 下一篇

猜你喜欢

热点阅读