app.vue
<template>
<div id="app">
<h2>{{message}}</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="counter++">+</button>
<button @click="counter--">-</button>
<hello-vuex :counter="counter"></hello-vuex>
</div>
</template>
<script>
import HelloVuex from './components/HelloWorld.vue'
export default {
name: 'App',
components:{
HelloVuex
},
data(){
return {
message:'我是app组件',
counter:0
}
}
}
</script>
<style>
</style>
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
index.js
import Vue from 'vue'
//第一步
import Vuex from 'vuex'
Vue.use(Vuex)
//创建对象
const store = new Vuex.store({
state: {
counter: 0
},
mutations: {
},
getters: {
},
modules: {
}
})
//
export default store
index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
HelloWorld.js
<template>
<div id="app">
<h2>{{$store.state.counter}}</h2>
</div>
</template>
<script>
export default {
name: 'HelloVuex',
props:{
counter:Number
},
data(){
return {
}
}
}
</script>
<style>
</style>
运行结果