Vue.observable怎么使用,解决处理什么问题
今天小编跟大家讲解下有关“Vue.observable怎么使用,解决处理什么问题”的内容 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了相关资料,希望小伙伴们看了有所帮助。
现在大家对于Vue.observable怎么使用,解决处理什么问题的内容应该都有一定的认识了吧,希望这篇能对大家有所帮助。最后,想要了解更多,欢迎关注博信,博信将为大家推送更多相关的文章。
随着组件的细化,就会遇到多组件状态共享的情况, 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>
显示效果
现在大家对于Vue.observable怎么使用,解决处理什么问题的内容应该都有一定的认识了吧,希望这篇能对大家有所帮助。最后,想要了解更多,欢迎关注博信,博信将为大家推送更多相关的文章。
版权声明
本文仅代表作者观点,不代表博信信息网立场。