Vue區域性元件資料共享Vue.observable()的使用
阿新 • • 發佈:2021-06-30
隨著元件的細化,就會遇到多元件狀態共享的情況, x當然可以解決這類問題,不過就像 Vuex官方文件所說的,如果應用不夠大,為避免程式碼繁瑣冗餘,最好不要使用它,今天我們介紹的是 vue. 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> vSWsY {{ count }}--{{ name }} <button @click="setCount(count + 1)">當前b元件中+1</button> <button @click="setCount(count - 1)">當前b元件中-1</bwww.cppcns.comutton> </div> </template> <script> import { store,changeName: mutations.changeName } }; </script> <style scoped> .bk { background: lightvSWsYgreen; } </style>
顯示效果
到此這篇關於Vue區域性元件資料共享Vue.observable()的使用的文章就介紹到這了,更多相關Vue.observable() 資料共享內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!