官网https://vuex.vuejs.org/zh/guide/modules.html
1.1 组件之间共享数据的方式
父向子传值:v-bind 属性绑定
子向父传值:v-on 事件绑定
兄弟组件之间共享数据(不相关组件):EventBus
$on. 接收数据的那个组件
$emit.发送数据的那个组件
1.2Vuex 是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享。
vuex统一管理状态的好处
1.能够在vuex中集中管理共享的数据,易于开发和后期维护
2.能够高效地实现组件之间的数据共享,提高开发效率
3.存储在vuex中的数据都是响应式的,能够实时的保持数据与页面的同步
只要数据改变了 页面就会自动的刷新
1.3什么样的数据适合存储到vuex中
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中,对于组件中的私有数据,依旧存储在组件自身的data中即可;
2.Vuex核心概念:state
2.1.State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
//创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
state: {count: 0}
})
组件中访问State中的数据的第一种方式
this.$store.state.全局数据名称
组件访问State数据的第二种方式
//1.从vuex中按需导入mapState函数
import {mapstate} from 'vuex'
通过刚才导入的mapstate函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:
//2.将全局数据,映射为当前组件的计算属性
computed: {
...mapstate(['count'])
//...代表展开运算符 把当前数据映射为当前组件的一个计算属性
}
{{count}}
3.Vuex核心概念:Mutation
作用:更改 Vuex 的 store 中的状态
1.只能通过mutation变更store数据,不可以直接操作store中的数据
2.通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
//触发mutation
methods: {
handle() {
//触发mutation的第一种方式
this.$store.commit('increment')
}
}
还可以在触发mutation时传递参数:提交载荷(Payload)
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, n) {
state.count += n
}
})
//触发mutation
methods: {
handle() {
//触发mutation的第一种方式
this.$store.commit('increment',5)
}
4.Vuex核心概念:Action
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementN (context) {
context.commit('increment')
}
}
})
//触发action
methods: {
handle() {
//触发mutation的第一种方式
this.$store.dispatch('incrementN')
}
action:支持异步操作 mutation只支持同步操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state,step) {
state.count+= step
}
},
actions: {
incrementN (context,step) {
setTimeout(()=>{
context.commit('increment',step)
})
}
})
//触发action
methods: {
handle() {
//触发mutation的第一种方式
this.$store.dispatch('incrementN',5)
}
5.Vuex核心概念:Getter
用于对store中的数据进行加工处理形成新的数据
1.Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
2.Store中数据发生变化,Getter的数据也会跟着变化
const store = new Vuex.Store({
state: {
count: 0
},
getters:{
showNum(state){
return '当前最新的数量时 【 ‘+state.count+’】'
}
}
})
在template直接引用:
<h3>{{store.getters.showNum}}</h3>
附录:
注意的是div占用一行,span不会占用一行,内容占多大宽度,span就有多宽。