Vue.observable的使用(小型状态管理器)

 随着项目组件的细化,经常性的遇到多组件之间状态共享的情况,之前可使用Vuex解决这类问题,不过参照Vuex官网介绍,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,今天了解一下Vue.js2.6 新版本中新增的一个东西Vue.observable(object),这个API的出现能替代以前使用vuex进行数据状态管理的方案。通过使用这个 api 我们可以应对一些简单的跨组件数据状态共享的情况。 官网描述如下 Vue.observable( object )

 observable()方法,用于设置监控属性,这样就可以监控view视图Module中的属性值的变化,从而就可以动态的改变某个元素中的值,监控属性的类型不变量而是一个函数,通过返回一个函数给viewModule对象中的属性,从而来监控该属性。

新建一个Vue Cli 使用一下Vue.Observable:

新建 store.js

import Vue from "vue"

export const state = Vue.observable({
    count: 0
})

页面1:

<template>
  <div class="observable">
    <h4>Observable1</h4>
    <div class="observable-layout">
      <button @click="add">add</button>
      <h4>{
   
   { count }}</h4>
      <button @click="reduce">reduce</button>
    </div>
    <div><button @click="go">go to Observable2</button></div>
  </div>
</template>

<script>
import { state } from "./store.js";
export default {
  data() {
    return {};
  },
  computed: {
    count() {
      return state.count;
    },
  },
  methods: {
    add() {
      state.count++;
    },
    reduce() {
      state.count--;
    },
    go() {
      this.$router.push({ name: "About" });
    },
  },
};
</script>

页面2:

<template>
  <div class="about">
    <div class="observable">
      <h4 style="color: red">Observable2</h4>
      <div class="observable-layout">
        <button @click="add">add</button>
        <h4>{
   
   { count }}</h4>
        <button @click="reduce">reduce</button>
      </div>
      <div><button @click="go">go back Observable1</button></div>
    </div>
  </div>
</template>
<script>
import { state } from "./observable/store.js";
export default {
  data() {
    return {};
  },
  computed: {
    count() {
      return state.count;
    },
  },
  methods: {
    add() {
      state.count++;
    },
    reduce() {
      state.count--;
    },
    go() {
      this.$router.push({ name: "Observable" });
    },
  },
  created() {
    console.log(this.count);
  },
};
</script>

 在 页面1 操作 count ,页面2 数据也会同步;

 

 也可以使用vuex自定义mutation来复用更改状态

import Vue from "vue"

export const state = Vue.observable({
    count: 0
})

export const mutations = {
    add(payload) {
        if (payload > 0) {
            state.count = payload
        }
    },
    reduce(payload) {
        if (payload > 0) {
            state.count = payload
        }
    }
}

具体使用:

<script>
import { state, mutations } from "./store.js";
export default {
  data() {
    return {};
  },
  computed: {
    count() {
      return state.count;
    },
  },
  methods: {
    add() {
      mutations.add(99);
    },
    reduce() {
      mutations.reduce(1);
    },
    go() {
      this.$router.push({ name: "About" });
    },
  },
};
</script>

不想 使用 vuex 做数据共享和更新时 ,可以使用 Vue.observable( Object ),实现多个组件之间数据的共享和更新,更加简洁的实现我们想要的效果

猜你喜欢

转载自blog.csdn.net/weixin_56650035/article/details/121778586