vue2的Vue.observable

vue2的Vue.observable

In Vue.js 2, Vue.observableis 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.observableusing :

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.observablethe method to create an dataobservable called with a property message. Then, we create a Vue instance appand assign datathe object to sharedDatathe property. In the createdhook , we print sharedData.messagethe value of .

When we modify the value data.messageof the , app.sharedData.messagethe value of is automatically updated because they refer to the same observable.

That's the basic usage Vue.observableof . 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 busor use vuex, but the implemented functions are not too complicated, and using the above two is a bit cumbersome. At this time, observableit is a good choice

create a jsfile

// 引入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
  }
}

.vueJust 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
  }
}

Guess you like

Origin blog.csdn.net/weixin_50975172/article/details/130955039