vue2的Vue.observable
In Vue.js 2, Vue.observable
is a method for creating observables. An observable object is an object that allows you to listen to its changes and trigger corresponding actions.
Here is an example Vue.observable
using :
import Vue from 'vue';
// 创建一个可观察对象
const data = Vue.observable({
message: 'Hello, Vue!'
});
// 在组件中使用可观察对象的属性
const app = new Vue({
data: {
sharedData: data
},
created() {
console.log(this.sharedData.message); // 输出: "Hello, Vue!"
}
});
// 修改可观察对象的属性
data.message = 'Hello, Vue 2!';
// 组件中的属性也会自动更新
console.log(app.sharedData.message); // 输出: "Hello, Vue 2!"
In the example above, we used Vue.observable
the method to create an data
observable called with a property message
. Then, we create a Vue instance app
and assign data
the object to sharedData
the property. In the created
hook , we print sharedData.message
the value of .
When we modify the value data.message
of the , app.sharedData.message
the value of is automatically updated because they refer to the same observable.
That's the basic usage Vue.observable
of . It allows us to create shared observables that keep data in sync between different components and trigger corresponding updates when the data changes.
scenes to be used
When non-parent-child components communicate, you can use the usual bus
or use vuex
, but the implemented functions are not too complicated, and using the above two is a bit cumbersome. At this time, observable
it is a good choice
create a js
file
// 引入vue
import Vue from 'vue
// 创建state对象,使用observable让state对象可响应
export let state = Vue.observable({
name: '张三',
'age': 38
})
// 创建对应的方法
export let mutations = {
changeName(name) {
state.name = name
},
setAge(age) {
state.age = age
}
}
.vue
Just use it directly in the file
<template>
<div>
姓名:{
{ name }}
年龄:{
{ age }}
<button @click="changeName('李四')">改变姓名</button>
<button @click="setAge(18)">改变年龄</button>
</div>
</template>
import { state, mutations } from '@/store
export default {
// 在计算属性中拿到值
computed: {
name() {
return state.name
},
age() {
return state.age
}
},
// 调用mutations里面的方法,更新数据
methods: {
changeName: mutations.changeName,
setAge: mutations.setAge
}
}