随着组件的细化,就会遇到多组件状态共享的情况, Vuex当然可以解决这类问题,不过就像 Vuex官方文档所说的,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,今天我们介绍的是 vue.js 2.6 新增加的 Observable API ,通过使用这个 api 我们可以应对一些简单的跨组件数据状态共享的情况。
首先创建一个 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; } }
然后再在组件中使用该对象
//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>
显示效果
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理