写在前:vue官方文档 地址
定义:Vuex是一个专为Vue.js应用程序开发的状态管理模式。
范围:组件之间共享的数据。
安装vuex
npm install vuex --save
引入:
import Vuex from 'vuex'
Vue.use(Vuex)
创建store对象
const store = new Vuex.Store({
state:{count: 0},
mutations: {
increment (state) {
state.count++
}
},
actions: {
}
})
//state 数据源
//mutations 同步方法集合
// actions 异步方法集合
// 如果想要改变state中的数据必须在mutations actions 中修改
挂载到vue实例中
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
vuex的核心概念:
1.数据源state
{{$store.state.count}}直接使用
// 引入
import { mapState} from 'vuex'
// 辅助函数
computed: {
...mapState(['count'])
},
//使用
{{count}}
2.通过mutation变更 store 数据
export default new Vuex.Store({
state: {
count: 1
},
mutations: {
add (state) {
state.count++
}
},
actions: {}
})
使用页面:
methods: {
addnumber () {
this.$store.commit('add')
}
}
重点:this.$store.commit('add') (使用commit 触发 mutations中的方法)
注:mutations 是同步的方法 actions 是异步得方法,调用mutations 中的方法
actions: {
addAsync (context, step) {
setTimeout(() => {
context.commit('add', step)
}, 1000)
}
}
使用 actions 中的函数
在methods中
subaycy () {
this.$store.dispatch('addAsync', 5)
}
另一种方式:
import { mapState, mapMutations, mapActions } from 'vuex'
methods: {
...mapMutations(['sub']),
...mapActions(['addAsync'])
// subnumber () {
// this.sub()
// },
subaycy () {
this.addAsync(5)
}
}
3.getters(包装state 中的数据)
getters: {
doneTodes: state => {
return '这是最新的count值【' + state.count +'】'
}
}
// 使用
{{$store.getters.doneTodes}}
// 另一中使用方式
//使用:
{{doneTodes}}
//引入
import { mapGetters } from 'vuex'
// 辅助函数
computed: {
...mapGetters(['doneTodes'])
},
注:小范围数据使用:
父向子传值: v-bind 属性绑定
子向父传值: v-on 事件绑定
兄弟组件之间共享数据: EventBus
$on 接收数据的那个组件
$emit 发送数据的那个组件