隨着組件的細化,就會遇到多組件狀態共享的狀況, Vuex固然能夠解決這類問題,不過就像 Vuex官方文檔所說的,若是應用不夠大,爲避免代碼繁瑣冗餘,最好不要使用它,今天咱們介紹的是 vue.js 2.6 新增長的 Observable API ,經過使用這個 api 咱們能夠應對一些簡單的跨組件數據狀態共享的狀況。vue
先看下官網描述,以下圖npm
observable()方法,用於設置監控屬性,這樣就能夠監控viewModule中的屬性值的變化,從而就能夠動態的改變某個元素中的值,監控屬性的類型不變量而是一個函數,經過返回一個函數給viewModule對象中的屬性,從而來監控該屬性。api
說那麼多,咱們在實際例子中嘗試玩一下:函數
搭建個簡單腳手架,在項目src目錄下創建store.js,在組件裏使用提供的 store和 mutation方法,同理其它組件也能夠這樣使用,從而實現多個組件共享數據狀態。spa
首先建立一個 store.js,包含一個 store和一個 mutations,分別用來指向數據和處理方法。code
//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; } }
而後在組件Home.vue中引用,在組件裏使用數據和方法:component
//Home.vue <template> <div class="container"> <home-header></home-header> <button @click="setCount(count+1)">+1</button> <button @click="setCount(count-1)">-1</button> <div>store中count:{{count}}</div> <button @click="changeName(name1)">父頁面修改name</button> <div>store中name:{{name}}</div> <router-link to="/detail" ><h5>跳轉到詳情頁</h5> </router-link> </div> </template> <script> import HomeHeader from '../components/HomeHeader' import {store,mutations} from '@/store' export default { data () { return { name1:'主頁的name' } }, components: { HomeHeader }, computed:{ count(){ return store.count }, name(){ return store.name } }, methods:{ setCount:mutations.setCount, changeName:mutations.changeName } } </script>
再定義一個子頁面觀察數據:router
//Detail.vue <template> <div class="detail"> <detail-header></detail-header> <button @click="changeName(name2)">子頁面修改name</button> <p>store中name:{{name}}</p> </div> </template> <script> import DetailHeader from '../components/DetailHeader' import {store,mutations} from '@/store' export default { components: { DetailHeader } , data(){ return { name2:'子頁的name' } }, computed:{ name(){ return store.name } }, methods:{ changeName:mutations.changeName } } </script>
子頁面顯示如圖:
對象
咱們簡單點擊下按鈕,改變下store中的數據,效果以下:
blog
最後補充一點,就是若是當前項目vue版本低於2.6,要使用Vue.observable(),就必需要升級,升級 vue 和 vue-template-compiler,二者的版本須要同步,若是不一樣步項目會報錯。
//升級vue版本 npm update vue -S 或者 yarn add vue -S npm update vue-template-compiler -D 或者 yarn add vue-template-compiler -D