- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- Vue局部組件數據共享Vue.observable()的使用
隨著(zhù)組件的細化,就會(huì )遇到多組件狀態(tài)共享的情況, Vuex當然可以解決這類(lèi)問(wèn)題,不過(guò)就像 Vuex官方文檔所說(shuō)的,如果應用不夠大,為避免代碼繁瑣冗余,最好不要使用它,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過(guò)使用這個(gè) api 我們可以應對一些簡(jiǎn)單的跨組件數據狀態(tài)共享的情況。
首先創(chuàng )建一個(gè) store.js,包含一個(gè) store和一個(gè) mutations,分別用來(lái)指向數據和處理方法。
//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>跨組件數據狀態(tài)共享 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>
顯示效果
到此這篇關(guān)于Vue局部組件數據共享Vue.observable()的使用的文章就介紹到這了,更多相關(guān)Vue.observable() 數據共享內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站