您的位置:首页 > 编程学习 > > 正文

vue各组件如何引用(Vue局部组件数据共享Vue.observable的使用)

更多 时间:2021-10-21 07:45:33 类别:编程学习 浏览量:1036

vue各组件如何引用

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>
      <li>
        <h1>跨组件数据状态共享 obserVable</h1>
        <li>
          <top></top>
          <bottom></bottom>
        </li>
      </li>
    </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>
      <li 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>
      </li>
    </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>
      <li class="bk">
        <h1>b组件</h1>
        {{ count }}--{{ name }}
        <button @click="setCount(count + 1)">当前b组件中+1</button>
        <button @click="setCount(count - 1)">当前b组件中-1</button>
      </li>
    </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局部组件数据共享Vue.observable的使用)

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