前言
隨着組件的細化,就會遇到多組件狀態共享的情況, Vuex當然可以解決這類問題,不過就像 Vuex官方文檔所說的,如果應用不夠大,為避免代碼繁瑣冗余,最好不要使用它,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過使用這個 api 我們可以應對一些簡單的跨組件數據狀態共享的情況。
用法
第一步
首先創建一個 store.js,包含一個 store和一個 mutations,分別用來指向數據和處理方法。
1 2 3 4 5 6 7 8 9 10 11 12
//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; } }
第二步
在組件xxx.vue中引用,在組件里使用數據和方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 大專欄 Vue.observable()使用方法 ss="line">19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<template> <div id="app"> <p>count:{{count}}</p> <p>name:{{name}}</p> <button @click="setCount(count+1)">+</button> <button @click="setCount(count-1)">-</button> <button @click="changeName(name2)">change</button> </div> </template> <script> import { store, mutations } from "./store"; export default { name: "App", data() { return { name2: '改變后的name' } } computed: { count() { return store.count; }, name() { return store.name } }, methods: { setCount: mutations.setCount, changeName: mutations.changeName } }; </script>
參考文章
使用Vue.observable()進行狀態管理