【问题标题】:Transfer Data From One Component to Another将数据从一个组件传输到另一个组件
【发布时间】:2019-12-26 18:38:56
【问题描述】:

我有一个组件调用我的后端 API。然后,这为我提供了用于组件的数据。我现在想创建另一个也使用该数据的组件。虽然我可以再做一个看起来很浪费的 api 调用。

所以,在 Profile.vue 中,我在 created() 函数中有这个。

<script>
import axios from 'axios';
import { bus } from '../main';


export default {
    name: 'Profile',
    data() {
        return {
            loading: false,
            error: null,
            profileData: null,
            getImageUrl: function(id) {
                return `http://ddragon.leagueoflegends.com/cdn/9.16.1/img/profileicon/` + id + `.png`;
            }
        }
    },
    beforeCreate() {
        //Add OR Remove classes and images etc..
    },
    async created() {
        //Once page is loaded do this
        this.loading = true;
        try {
            const response = await axios.get(`/api/profile/${this.$route.params.platform}/${this.$route.params.name}`);
            this.profileData = response.data;
            this.loading = false;
            bus.$emit('profileData', this.profileData)

        } catch (error) {
            this.loading = false;
            this.error = error.response.data.message;
        }
    }
};
</script>

然后我有另一个使用 Vue 路由器连接的子组件,这是为了显示更多信息。

MatchHistory 组件

<template>
  <section>
      <h1>{{profileDatas.profileDatas}}</h1>
  </section>
</template>

<script>
import  { bus } from '../main';

export default {
    name: 'MatchHistory',
    data() {
        return {
            profileDatas: null
        }
    },
    beforeCreate() {
        //Add OR Remove classes and images etc..
    },
    async created() {
        bus.$on('profileData', obj => {
            this.profileDatas = obj;
        });
    }
};
</script>

所以,我想获取信息并显示我传输的数据。

【问题讨论】:

    标签: vue.js components vue-component vue-router


    【解决方案1】:

    你可以使用vm.$emit创建一个Eventbus

    // split instance
    const EventBus = new Vue({}) 
    class IApp extends Vue {}
    
    IApp.mixin({
    
      beforeCreate: function(){
        this.EventBus = EventBus
      }
    })
    
    
    const App = new IApp({
      created(){
        this.EventBus.$on('from-mounted', console.log)
      },
      mounted(){
        this.EventBus.$emit('from-mounted', 'Its a me! Mounted')
      }
    }).$mount('#app')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app"></div>

    further readings

    【讨论】:

      【解决方案2】:

      您可以使用VUEX,它是 Vue 的状态管理系统。

      当您调用 api 并获取您需要的数据时,您可以 COMMIT a MUTATION 并将您的数据传递给它。它将做什么,它将更新您的STATE,并且您的所有组件都可以访问其状态(数据)

      在您的async created() 中,当您收到响应时,只需向您的商店提交突变以更新状态。 (此处省略示例,因为 vuex 存储需要配置才能执行突变)

      然后在你的子组件中,

      data(){
      return {
         profileDatas: null
      }
      },
      async created() {
          this.profileDatas = $store.state.myData;
      }
      

      在您的情况下,这似乎有点矫枉过正,但在处理需要跨多个组件共享的外部数据时,这种方法非常有用

      【讨论】:

      • myData 将是您为状态变量指定的名称
      【解决方案3】:

      我的假设是基于这样一个事实,即这些组件是为两个单独的路由定义的,并且根据您的应用程序设计,事件总线可能不适用于您的情况。有几种方法可以解决这个问题。下面列出了其中的两个。

      1. Vuex(用于 Vue 状态管理)
      2. 任何本地存储选项 - LocalStorage/SessionStorage/IndexDB 等

      有关 VueX 的更多信息,请访问https://vuex.vuejs.org/

      有关 Localstorage 的更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

      有关会话存储的更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

      任何选项的流程都几乎相同。

      1. 使用 axios 从 API 获取数据,就像您在 Profile.vue 中所做的那样
      2. 使用 VueX 或本地/会话存储存储检索到的数据
      3. 在 MatchHistory.vue 组件的 created 方法中从 Vuex 或本地/会话存储中检索数据

      对于本地/会话存储选项,您必须将对象转换为 json 字符串,因为只有字符串可以存储在存储中。见下文。

      在 Profile.vue 中(创建)

      const response = await axios.get(........)
      if(response){
          localStorage.setItem('yourstoragekey', JSON.stringify(response));
      }
      

      在 MatchHistory.Vue(创建)中

      async created() {
          var profileData = localStorage.getItem('yourstoragekey')
          if(profileData){
              profileData = JSON.parse(profileData );
              this.profileData = profileData 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-09
        • 2022-08-14
        • 2018-05-02
        • 2021-12-30
        • 1970-01-01
        • 2019-12-16
        • 2021-04-16
        相关资源
        最近更新 更多