0
votes

I am a beginner in vuejs.

I have an issue with some practice about vue-router nested route.

Just in case, This is a nested route config.

const router = new Router({
    routes: [
        {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true
            },
            children: [
                {
                    path: 'overview',
                    name: 'Overview',
                    component: Overview,
                    meta: {
                        requiresAuth: true
                    }
                }
            ]
        }
    ]
})

If I want to pass data from a child route (overview) to parent route (dashboard)

How should I handle it ?

I don't want the url have any change (/dashboard/overview), just receive the data params from child route.

1

1 Answers

3
votes

You might want to consider using Vuex as a means of sharing state across different components (or maybe not if you're a beginner).

Alternatively you can just emit an event in the child component:

Vue.use(VueRouter);

var Parent = {
  template: '<router-view @data="onData"></router-view>',
  methods: {
    onData(data) {
      alert('Got data from child: ' + data);
    },
  },
};

var Child = {
  template: '<div><input v-model="text"><button @click="onClick">Click Me</button></div>',
  data() {
    return {
      text: 'Hello',
    };
  },
  methods: {
    onClick() {
      this.$emit('data', this.text);
    },
  },
};

var router = new VueRouter({
  routes: [
    {
      path: '',
      component: Parent,
      children: [
        {
          path: '',
          component: Child,
        },
      ],
    },
  ],
});

new Vue({
  el: '#app',
  router,
});
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>

<div id="app">
  <router-view></router-view>
</div>