1
votes

I'm creating app by using Vue Ionic and trying to change page by modal controller provided by ionic like the following code.

const modal = await this.$ionic.modalController.create({
  component: NewPageComponent
})
modal.present()

Then NewPageComponent is opened without problem in <ion-modal></ion-modal>. But when I try to confirm $route and $router in NewPageComponent, NewPageComponent doesn't have these.

NewPageComponent

export default {
  created () {
    console.log(this.$route) // undefined
    console.log(this.$router) // undefined
  }
}

Vue Components opened in <ion-modal></ion-modal> don't seem to have $route and $router. But others have these without problem. For example I can see $route and $router in App.vue.

App.vue

<template>
  <ion-app>
    <v-app>
      <span>App</span>
    </v-app>
  <ion-app>
</template>

<script>
export default {
  created () {
    console.log(this.$route) // this.$route exists
    console.log(this.$router) // this.$router exists
  }
}
</script>

Of course I have registered router in main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Ionic from '@ionic/vue'
import './registerServiceWorker'
import './plugins/ionic.js'


Vue.use(Ionic)
Vue.config.productionTip = false

new Vue({
  router, // I have set router like this
  render: h => h(App)
}).$mount('#app')

Is there any way to make Vue Components opened in <ion-modal></ion-modal> like NewPageComponent have $route and $router?

1
not sure where you got this code from but it is all wrong. I suggest you start with the ionic starter templates and the documentation on creating modalsAaron Saunders

1 Answers

0
votes

Internally Ionic uses another Vue instance. When you creating new modal it is placed in this instance without router that is registered in main app. I recommend you to use event bus pattern to communicate between components. It's pretty simple:

EventBus.js

import Vue from 'vue'
export const EventBus = new Vue()

Then in main app you can listen to custom events:

App.vue

import {EventBus} from './EventBus.js'
//...
created() {
  EventBus.$on('change-route', this.handleRouteChange)
  EventBus.$on('change-params', this.handleParamsChange)
},
beforeDestroy() {
  EventBus.$off('change-route', this.handleRouteChange)
  EventBus.$off('change-params', this.handleParamsChange)
},
methods: {
  handleRouteChange(page) {
    // here you can normally access this.$router
    this.$router.push(page)
  },
  handleParamsChange(params) {
    this.$router.push({params:params})
  }
},

NewPageComponent.vue

import {EventBus} from './EventBus.js'
//...
methods: {
  changePage() {
    EventBus.$emit('change-page', '/new-page')

    // If you want to change page named route with params:
    // EventBus.$emit('change-page', {name:'product', params: {id: 10}})
  },
  updateParams() {
    EventBus.$emit('change-params', {id: 1010})
  } 
}