Vue局部组件数据共享Vue.observable()的使用

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue局部组件数据共享Vue.observable()的使用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

随着组件的细化,就会遇到多组件状态共享的情况, Vuex当然可以解决这类问题,不过就像 Vuex官方文档所说的,如果应用不够大,为避免代码繁琐冗余,最好不要使用它,今天我们介绍的是 vue.js 2.6 新增加的 Observable API ,通过使用这个 api 我们可以应对一些简单的跨组件数据状态共享的情况。

创建store对象

首先创建一个 store.js,包含一个 store和一个 mutations,分别用来指向数据和处理方法。

//store.js
import Vue from 'vue';

export let store =Vue.observable({count:0,name:'李四'});
export let mutations={
    setCount(count){
        store.count=count;
    },
    changeName(name){
        store.name=name;
    }
}

把store对象应用在不同组件中

然后再在组件中使用该对象

//obserVable.vue
<template>
  <div>
    <h1>跨组件数据状态共享 obserVable</h1>
    <div>
      <top></top>
      <bottom></bottom>
    </div>
  </div>
</template>

<script>
import  top  from './components/top.vue';
import  bottom  from './components/bottom.vue';
export default {
  name: 'obserVable',
  components: {
    top,
    bottom
  }
};
</script>

<style scoped>
</style>
//组件a
<template>
  <div class="bk">
    <span
      ><h1>a组件</h1>
      {{ count }}--{{ name }}</span
    >
    <button @click="setCount(count + 1)">当前a组件中+1</button>
    <button @click="setCount(count - 1)">当前a组件中-1</button>
  </div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
  computed: {
    count() {
      return store.count;
    },
    name() {
      return store.name;
    }
  },
  methods: {
    setCount: mutations.setCount,
    changeName: mutations.changeName
  }
};
</script>
<style scoped>
.bk {
  background: lightpink;
}
</style>
//组件b
<template>
  <div class="bk">
    <h1>b组件</h1>
    {{ count }}--{{ name }}
    <button @click="setCount(count + 1)">当前b组件中+1</button>
    <button @click="setCount(count - 1)">当前b组件中-1</button>
  </div>
</template>
<script>
import { store, mutations } from '@/store';
export default {
  computed: {
    count() {
      return store.count;
    },
    name() {
      return store.name;
    }
  },
  methods: {
    setCount: mutations.setCount,
    changeName: mutations.changeName
  }
};
</script>
<style scoped>
.bk {
  background: lightgreen;
}
</style>

显示效果

在这里插入图片描述

到此这篇关于Vue局部组件数据共享Vue.observable()的使用的文章就介绍到这了,更多相关Vue.observable() 数据共享内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Vue局部组件数据共享Vue.observable()的使用全部内容,希望文章能够帮你解决Vue局部组件数据共享Vue.observable()的使用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: