随笔 - 748  文章 - 1  评论 - 107  阅读 - 34万

【转】[Vue] 数据的共享

来自:kimi.ai

在 Vue.js 中,共享数据的读写通常涉及到多个组件之间的数据共享。Vue 提供了多种方式来实现组件间的数据共享,包括 props、事件、Vuex 和 provide/inject 等。以下是这些方法的详细介绍和示例代码。

1. 使用 props 和事件

props 是父组件向子组件传递数据的方式,而事件($emit)是子组件向父组件传递数据的方式。

示例代码

父组件:
vue复制
<template>
  <div>
    <h1>Parent Component</h1>
    <p>Parent Data: {{ parentData }}</p>
    <ChildComponent :childData="parentData" @updateParentData="updateParentData" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentData: 'Initial Data'
    };
  },
  methods: {
    updateParentData(newData) {
      this.parentData = newData;
    }
  }
};
</script>
子组件:
vue复制
<template>
  <div>
    <h2>Child Component</h2>
    <p>Child Data: {{ childData }}</p>
    <button @click="updateParent">Update Parent Data</button>
  </div>
</template>

<script>
export default {
  props: {
    childData: String
  },
  methods: {
    updateParent() {
      this.$emit('updateParentData', 'New Data from Child');
    }
  }
};
</script>

2. 使用 Vuex

Vuex 是 Vue.js 的状态管理库,适用于大型应用中跨组件共享状态的场景。Vuex 提供了集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

示例代码

安装 Vuex:
bash复制
npm install vuex@next
Vuex Store:
JavaScript复制
// store/index.js
import { createStore } from 'vuex';

export default createStore({
  state: {
    sharedData: 'Initial Shared Data'
  },
  mutations: {
    updateSharedData(state, newData) {
      state.sharedData = newData;
    }
  },
  actions: {
    updateSharedData({ commit }, newData) {
      commit('updateSharedData', newData);
    }
  },
  getters: {
    sharedData: (state) => state.sharedData
  }
});
主文件:
JavaScript复制
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);
app.use(store);
app.mount('#app');
组件中使用 Vuex:
vue复制
<template>
  <div>
    <h1>Component A</h1>
    <p>Shared Data: {{ sharedData }}</p>
    <button @click="updateSharedData('New Data from Component A')">Update Shared Data</button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['sharedData'])
  },
  methods: {
    ...mapActions(['updateSharedData'])
  }
};
</script>

3. 使用 provide 和 inject

provideinject 是 Vue.js 提供的依赖注入机制,适用于父子组件之间或跨层级组件之间的数据共享。

示例代码

父组件:
vue复制
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  provide() {
    return {
      sharedData: this.sharedData,
      updateSharedData: this.updateSharedData
    };
  },
  data() {
    return {
      sharedData: 'Initial Shared Data'
    };
  },
  methods: {
    updateSharedData(newData) {
      this.sharedData = newData;
    }
  }
};
</script>
子组件:
vue复制
<template>
  <div>
    <h2>Child Component</h2>
    <p>Shared Data: {{ sharedData }}</p>
    <button @click="updateSharedData('New Data from Child')">Update Shared Data</button>
  </div>
</template>

<script>
export default {
  inject: ['sharedData', 'updateSharedData']
};
</script>

4. 使用全局事件总线

全局事件总线是一种简单的事件驱动机制,适用于组件间通信。不过,它在 Vue 3 中已被废弃,但在 Vue 2 中仍然可以使用。

示例代码

创建事件总线:
JavaScript复制
// eventBus.js
import Vue from 'vue';
export const EventBus = new Vue();
组件中使用事件总线:
vue复制
<template>
  <div>
    <h1>Component A</h1>
    <p>Shared Data: {{ sharedData }}</p>
    <button @click="updateSharedData('New Data from Component A')">Update Shared Data</button>
  </div>
</template>

<script>
import { EventBus } from './eventBus.js';

export default {
  data() {
    return {
      sharedData: ''
    };
  },
  created() {
    EventBus.$on('updateSharedData', (newData) => {
      this.sharedData = newData;
    });
  },
  methods: {
    updateSharedData(newData) {
      EventBus.$emit('updateSharedData', newData);
    }
  },
  beforeDestroy() {
    EventBus.$off('updateSharedData');
  }
};
</script>

总结

  • props 和事件:适用于父子组件间的数据共享。
  • Vuex:适用于大型应用中跨组件共享状态。
  • provideinject:适用于父子组件或跨层级组件间的数据共享。
  • 全局事件总线:适用于简单的组件间通信,但在 Vue 3 中不推荐使用。
根据你的具体需求选择合适的方式。对于复杂的应用,推荐使用 Vuex 来管理共享状态。
posted on   z5337  阅读(11)  评论(3编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2024-02-05 [转][Centos]安装 gogs
2024-02-05 【转】【Centos】配置静态IP
2024-02-05 【转】【Centos】安装 VMware Tools
2024-02-05 [转][Linux]安装 Centos
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示