将数据从一个组件传输到另一个组件

时间:2019-08-21 13:06:28

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

我有一个组件可以调用我的后端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>

因此,我想获取信息并显示传输过来的数据。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我的假设基于以下事实:这些组件是为两条单独的路线定义的,根据应用程序的设计,事件总线可能无法满足您的情况。有几种解决方法。下面列出了其中两个。

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

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

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

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

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

  1. 就像上面在Profile.vue中所做的一样,使用axios从API获取数据
  2. 使用VueX或本地/会话存储存储检索到的数据
  3. 使用MatchHistory.vue组件的已创建方法从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 
    }
}

答案 2 :(得分:0)

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

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

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

然后在您的子组件中,

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

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