Vuex最基本樣例

經過vue-cli創建基本腳手架(須要安裝vuex),須要新建一個store.js文件。基本目錄以下javascript

1,store.js文件代碼:vue

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
	count: 5
}

const mutations = {
	add(state){
		state.count += 1
	},
	reduce(state){
		state.count -= 1
	}
}
export default new Vuex.Store({
 	state,
 	mutations
})

 2,App.vue代碼:java

<template>
  <div id="app">
    <p>hello vuex</p>
    <p>{{$store.state.count}}</p>
    <button @click = "$store.commit('add')">+</button>
    <button @click = "$store.commit('reduce')">-</button>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</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>

 3,入口文件main.js代碼:web

import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

 運行結果爲:vuex

默認顯示爲數字5,點擊+或者-,執行相應的加減操做。vue-cli

相關文章
相關標籤/搜索