随着组件的细化,很多时候都需要处理组件状态共享的情况, Vuex可以轻松解决这类问题,不过就像 Vuex官方文档所说的,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,接下来介绍的是 vue.js 2.6 新增加的 Observable API ,通过使用这个 api 我们可以应对一些简单的跨组件数据状态共享的情况。
// 创建store目录,store目录下创建index.js
import Vue from 'vue'
export const store = Vue.observable({
count: 0,
name: '李四'
})
export const mutations = {
setCount (count) {
store.count = count
},
changeName (name) {
store.name = name
}
}
// 在组件中使用
<template>
<div class="container">
<button @click="setCount(count+1)">count++</button>
</div>
</template>
<script>
import { store, mutations } from '@/store/index'
export default {
computed: {
// 如果store中的数据发生变化重新计算
count () {
return store.count
},
name () {
return store.name
}
},
methods () {
// 将store中的mutations方法赋值拿到
setCount: mutations.setCount
}
}
</script>
// 或者可以绑定到Vue的原型上
// store/index.js
import Vue from 'vue'
const store = {
state: Vue.observable({
count: 0,
name: '李四'
}),
mutations: {
setCount (count) {
store.state.count = count
},
changeName (name) {
store.state.name = name
}
}
}
export default store
// 在组件中使用
<script>
export default {
created () {
// 通过this.store来调用
console.log(this.store)
}
}
</script>
总结:
体量比vuex小,使用维护成本相对较低
用于数据共享,当十几个组件同时共用一套数据时候,把数据独立抽离出来,方便维护也可以实现多个组件之间数据的共享和更新