How to pass data from one view to another with the vue-router

Viewed 19779

When using the vue-router with .vue files, there is no documented way to pass data from one view/component to another.

Let's take the following setup...

main.js:

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

let routes = [
    {
        path: '/page1',
        component: require('./views/Posts.vue')
    },
    {
        path: '/page2',
        component: require('./views/EditPost.vue')
    }
];

let router = new VueRouter({
    routes
});

new Vue({
    el: '#main',
    router
});

Posts.vue:

<template>
    <div>
        Posts.vue passing the ID to EditPost.vue: {{ postId }}
    </div>
</template>

<script>
    export default {
        data() {
            return {
                allPostsHere: // Whatever...
            }
        }
    }
</script>

EditPost.vue:

<template>
    <div>
        EditPost.vue received ID from Posts.vue: {{ receivedId }}
    </div>
</template>

<script>
    export default {
        data() {
            return {
                receivedId: // This is where I need the ID from Posts.vue
            }
        }
    }
</script>

Please note: It is not possible to receive the ID directly from the EditPost.vue, because it has to be selected from Posts.vue.

Question: How can I pass the ID from one view/component to the other?

3 Answers
Related