Vue局部組件數(shù)據(jù)共享Vue.observable()的使用
隨著組件的細(xì)化,就會(huì)遇到多組件狀態(tài)共享的情況, Vuex當(dāng)然可以解決這類問(wèn)題,不過(guò)就像 Vuex官方文檔所說(shuō)的,如果應(yīng)用不夠大,為避免代碼繁瑣冗余,最好不要使用它,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過(guò)使用這個(gè) api 我們可以應(yīng)對(duì)一些簡(jiǎn)單的跨組件數(shù)據(jù)狀態(tài)共享的情況。
創(chuàng)建store對(duì)象首先創(chuàng)建一個(gè) store.js,包含一個(gè) store和一個(gè) mutations,分別用來(lái)指向數(shù)據(jù)和處理方法。
//store.jsimport 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對(duì)象應(yīng)用在不同組件中
然后再在組件中使用該對(duì)象
//obserVable.vue<template> <div> <h1>跨組件數(shù)據(jù)狀態(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)'>當(dāng)前a組件中+1</button> <button @click='setCount(count - 1)'>當(dāng)前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)'>當(dāng)前b組件中+1</button> <button @click='setCount(count - 1)'>當(dāng)前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局部組件數(shù)據(jù)共享Vue.observable()的使用的文章就介紹到這了,更多相關(guān)Vue.observable() 數(shù)據(jù)共享內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. el-input無(wú)法輸入的問(wèn)題和表單驗(yàn)證失敗問(wèn)題解決2. 父div高度不能自適應(yīng)子div高度的解決方案3. ASP動(dòng)態(tài)include文件4. 不要在HTML中濫用div5. Vue中原生template標(biāo)簽失效如何解決6. XML入門的常見(jiàn)問(wèn)題(三)7. XML 非法字符(轉(zhuǎn)義字符)8. vue跳轉(zhuǎn)頁(yè)面常用的幾種方法匯總9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. js開(kāi)發(fā)中的頁(yè)面、屏幕、瀏覽器的位置原理(高度寬度)說(shuō)明講解(附圖)
