Vue.observable(object)
vue2.6 新增
定义
官方说法
让一个对象可响应。Vue 内部会用它来处理 data 函数返回的对象。
返回的对象可以直接用于渲染函数和计算属性内,并且会在发生变更时触发相应的更新。也可以作为最小化的跨组件状态存储器,用于简单的场景:
1.用于渲染函数(官方案例)
const state = Vue.observable({ count: 0 })
const Demo = {
render(h) {
return h('button', {
on: { click: () => { state.count++ }}
}, `count is: ${state.count}`)
}
}
2.用于计算属性
官方定义说其返回对象可以用于计算属性中,即
// test/demo.js
import Vue from 'vue'
const state = Vue.observable({
name: 'tt',
age: 12
})
export = { state }
// test/index.vue
<template>
<div>{{ storeName }}</div>
</template>
import { state } from './demo.js'
export default {
computed: {
storeName: function() {
return state.name
}
}
}
3.用作最小化的跨组件状态存储器
简化版vuex?
写个demo试试
// src\min-store\store.js
import Vue from 'vue'
const state = Vue.observable({
name: 'ly',
age: 12
})
const mutations = {
changeName: function(name) {
state.name = name
},
changeAge: function(age) {
state.age = age
}
}
export { state, mutations }
// src\App.vue
<template>
<div id="app">
<HelloWorld></HelloWorld>
====================<br>
<button @click="changeName()">button</button>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld'
import { mutations} from '@/min-store/store.js'
export default {
components: {
HelloWorld
},
created() {},
methods: {
changeName() {
mutations.changeName('tt')
},
}
};
</script>
// src\components\HelloWorld.vue
<template>
<div>
{{ storeName }}
</div>
</template>
<script>
import { state } from '@/min-store/store.js'
export default {
computed: {
storeName: function() {
return state.name
}
}
};
</script>
最后
笔者记录用,后续可能会更新