Vue局部組件數據共享Vue.observable()的使用
隨著組件的細化,就會遇到多組件狀態共享的情況, Vuex當然可以解決這類問題,不過就像 Vuex官方文檔所說的,如果應用不夠大,為避免代碼繁瑣冗余,最好不要使用它,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過使用這個 api 我們可以應對一些簡單的跨組件數據狀態共享的情況。
創建store對象首先創建一個 store.js,包含一個 store和一個 mutations,分別用來指向數據和處理方法。
//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對象應用在不同組件中
然后再在組件中使用該對象
//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局部組件數據共享Vue.observable()的使用的文章就介紹到這了,更多相關Vue.observable() 數據共享內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問題2. 完美解決vue 中多個echarts圖表自適應的問題3. 在Chrome DevTools中調試JavaScript的實現4. Springboot 全局日期格式化處理的實現5. SpringBoot+TestNG單元測試的實現6. Java使用Tesseract-Ocr識別數字7. vue實現web在線聊天功能8. JAMon(Java Application Monitor)備忘記9. IntelliJ IDEA設置自動提示功能快捷鍵的方法10. Python使用urlretrieve實現直接遠程下載圖片的示例代碼
