当前位置:   article > 正文

vue中多组件状态共享的两种方法_vue动态加载的 umd.js 如何共享主体store

vue动态加载的 umd.js 如何共享主体store

一、vuex(较大项目)

使用方法:占坑,网上很多 

二、Observable API

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

如下这个例子,我们将在组件外创建一个 store,然后在 App.vue组件里面使用 store.js 提供的 storemutation方法,同理其它组件也可以这样使用,从而实现多个组件共享数据状态。

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

  1. import Vue from 'vue';
  2. export const store = Vue.observable({ count: 0 });
  3. export const mutations = {
  4. setCount(count) {
  5. store.count = count;
  6. }
  7. };

然后在 App.vue里面引入这个 store.js,在组件里面使用引入的数据和方法

  1. <template>
  2. <div id="app">
  3. <img src="./assets/logo.png">
  4. <p>count: {{ count }}</p>
  5. <!-- <router-view/> -->
  6. <button @click="setCount(count + 1)">+1</button>
  7. <button @click="setCount(count - 1)">-1</button>
  8. </div>
  9. </template>
  10. <script>
  11. import { store, mutations } from './store';
  12. export default {
  13. name: 'APP',
  14. computed: {
  15. count() {
  16. return store.count;
  17. }
  18. },
  19. methods: {
  20. setCount: mutations.setCount
  21. }
  22. }

ps:代码案例来自公众号JavaScript 

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/280256
推荐阅读
相关标签
  

闽ICP备14008679号