1.安装vuex
npm install vuex --save
2. 在src目录下创建store文件夹
在store文件夹下创建index.js文件
index.js文件内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//存放全局公用数据
state: {
city: '北京'
}
})
3. 在main.js中引入index.js
import store from './store'
new Vue({
el: '#app',
router,
store, //这里一定要引入
components: { App },
template: '<App/>'
})
3. 在组件中使用公用的数据
在每个子组件中都可以通过this.$store.state获得公用数据
<div class="button">{
{ this.$store.state.city }}</div>
3. 在组件中修改数据
例如城市列表页面点击某个城市的时候将公用数据修改为点击的城市名称,并且首页的城市名称也随之改变
修改数据的时候必会调用actions事件,而调用此事