项目不大的情况下,使用Observable来实现状态共享不失为一个选择。
先来看看官方资料:
Vue.observable( object ) 2.6.0 新增
参数 :{Object} object
用法 :让一个对象可响应。Vue 内部会用它来处理 data 函数返回的对象
此API为2.6版本新增, 那么低版本是不兼容, 会报出以下错误:
vue__.default.observable is not a funcion
解决方法是将Vue升级到^2.6.0 即可。
写个Demo看看
1.创建store
// 文件路径 - /store/store.js
import Vue from 'vue'
export const store = Vue.observable({ count: 0 })
export const mutations = {
setCount (count) {
store.count = count
}
}
2. 使用
<template>
<div>
<label for="bookNum">数 量</label>
<button @click="setCount(count+1)">+</button>
<span>{{count}}</span>
<button @click="setCount(count-1)">-</button>
</div>
</template>
<script>
import { store, mutations } from '../store/store' // Vue2.6新增API Observable
export default {
name: 'Add',
computed: {
count () {
return store.count
}
},
methods: {
setCount: mutations.setCount
}
}
</script>
怎么样,很简单吧。。