1、安装vuex依赖包
npm install vuex --save
2、导入vuex包
在store.js中导入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { },
mutations: { },
actions: { }
})
3、创建store对象
const store = new Vuex.Store({
// state 中存放的就是全局共享的数据
state:{count:0}
})
4、将store对象挂载到vue实例中
new Vue({
el:'#app',
render:h => h(app),
router,
// 将创建的共享数据对象,挂载到vue实例中
// 所有的组件,就可以直接从store中获取全局的数据了
store
})
二、Vuex 核心概念:
Vuex中的主要核心概念如下:
State
Mutation
Action
Getter
2.1、State 提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
// state 中存放的就是全局共享的数据
state:{count:0}
})
第一种方式:组件访问State中数据:
方式:this.$store.state.全局数据名称
store.js中代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
组件Addition.vue中代码如下:
<template>
<div>
<!-- 访问数据的第一种方式 -->
<h3>当前最新的count值为:{{$store.state.count}}</h3>
<button>+1</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
};
</script>
第二种方式:组件访问State中数据:
// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:
// 2.将全局数据,映射为当前组件的计算属性
computed:{
...mapState(['count'])
}
代码示例:
store.js中代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
组件subtraction.vue中代码如下:
<template>
<div>
<!-- 访问数据的第二种方式 -->
<h3>当前最新的count值为:{{ count }}</h3>
<button>-1</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data() {
return {};
},
computed: {
...mapState(['count'])
}
};
</script>