随着组件的细化,就会遇到多组件状态共享的情况, Vuex当然可以解决这类问题,不过就像 Vuex官方文档所说的,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,今天我们介绍的是 vue.js 2.6 新增加的 Observable API ,通过使用这个 api 我们可以应对一些简单的跨组件数据状态共享的情况。
创建store对象
首先创建一个 store.js,包含一个 store和一个 mutations,分别用来指向数据和处理方法。
//store.js
import Vue from 'vue';
export let store =Vue.observable({count:0,name:'李四'});
export let mutations={
setCount(count){
store.count=count;
},
changeName(name){
store.name=name;
}
}
把store对象应用在不同组件中
然后再在组件中使用该对象
//obserVable.vue
<template>
<div>
<h1>跨组件数据状态共享 obserVable</h1>
<div>
<top></top>
<bottom></bottom>
</div>
</div>
</template>
<script>
import top from './components/top.vue';
import bottom from './components/bottom.vue';
export default {
name: 'obserVable',
components: {
top,
bottom
}
};
</script>
<style scoped>
</style>
//组件a
<template>
<div class="bk">
<span
><h1>a组件</h1>
{{ count }}--{{ name }}</span
>
<button @click="setCount(count + 1)">当前a组件中+1</button>
<button @click="setCount(count - 1)">当前a组件中-1</button>
</div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
computed: {
count() {
return store.count;
},
name() {
return store.name;
}
},
methods: {
setCount: mutations.setCount,
changeName: mutations.changeName
}
};
</script>
<style scoped>
.bk {
background: lightpink;
}
</style>
//组件b
<template>
<div class="bk">
<h1>b组件</h1>
{{ count }}--{{ name }}
<button @click="setCount(count + 1)">当前b组件中+1</button>
<button @click="setCount(count - 1)">当前b组件中-1</button>
</div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
computed: {
count() {
return store.count;
},
name() {
return store.name;
}
},
methods: {
setCount: mutations.setCount,
changeName: mutations.changeName
}
};
</script>
<style scoped>
.bk {
background: lightgreen;
}
</style>