使用发射器在 Vue3 组件之间交换数据并重定向到另一个路由

问题描述 投票:0回答:1

我的第一个 Vue3 组件有一个按钮。按下该按钮时,数据应发送到作为第二个组件的子组件的另一个组件。然后它应该被重定向到另一个应该显示数据的页面。

export default {
  name: 'Text Field',
  inject: ['emitter'],
  data(){
    return{
      searchText: '',
      locations: [],
      initialCoordinates: [139.753, 35.6844],
  }
},
methods: {
// other methods skipped
submit() {
    this.initialCoordinates = [longitude, latitude]

    this.emitter.emit('Coordinates', this.initialCoordinates)
    
    this.$router.push('/test');
  },
// rest of the component

在第二个组件的子组件中,我尝试从发射器接收数据,然后将其重定向到包括该组件的其他页面。

<script>
export default {
    name: "test_emitter",
    inject: ["emitter"],
    mounted(){
      this.emitter.on('Coordinates', (coordinates) => {
      alert('test' + coordinates)
    });
    }
}
</script>

但是,即使第一个组件发出事件,第二个组件的子组件中的警报“测试”也永远不会显示。

我认为这与重定向有关,但没有显示任何日志记录或警报,表明随时收到了数据。

我还测试了相同的发射器配置,无需重定向,并将数据发送到同一路由的当前组件的子组件,并且它可以工作。所以我很高兴收到任何提示或建议:)

redirect vuejs3 vue-component eventemitter
1个回答
0
投票

我使用Vue Router的beforeRouteLeave守卫解决了这个问题:

this.$router.push({ name: 'newRoute', query: { coordinates: this.coordinates } });

这样做,我可以路由到另一个页面,同时向路由到的组件提供数据。

© www.soinside.com 2019 - 2024. All rights reserved.