如何使用 vue-router 将数据从一个视图传递到另一个视图

Tho*_*sla 5 vue.js vue-router vue-component vuejs2

使用vue-routerwith.vue文件时,没有记录的方法可以将数据从一个视图/组件传递到另一个视图/组件。

让我们进行以下设置...

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
});
Run Code Online (Sandbox Code Playgroud)

帖子.vue

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

<script>
    export default {
        data() {
            return {
                allPostsHere: // Whatever...
            }
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

编辑帖子.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>
Run Code Online (Sandbox Code Playgroud)

请注意:不可能直接从 接收 ID EditPost.vue,因为必须从 中选择它Posts.vue

问题:如何将 ID 从一个视图/组件传递到另一个视图/组件?

Kub*_*ski 4

路由只能通过 URL 访问,并且 URL 必须是用户可以在 URL 栏中输入的内容,因此要将变量从一个视图组件传递到另一个视图组件,您必须使用路由参数

我假设您在组件中有一个帖子列表Posts,并且想要更改页面以编辑EditPost组件中的特定帖子。

最基本的设置是在帖子列表中添加一个链接以重定向到编辑页面:

<div v-for="post in posts">
    {{ post.title }}
    <router-link :to="'/post/' + post.id + '/edit'">Edit</router-link>
</div>
Run Code Online (Sandbox Code Playgroud)

您的路线将如下所示:

[
    {
        path: '/posts',
        component: require('./views/Posts.vue'),
    },
    {
        path: '/post/:postId/edit',
        component: require('./views/EditPost.vue'),
        props: true,
    },
]
Run Code Online (Sandbox Code Playgroud)

配置props选项只是通知 Router 将路由参数转换为组件 props。有关更多信息,请参阅将 props 传递给路由组件

然后EditPost你会接受 id 并从服务器获取帖子。

export default {
    props: ['postId'],

    data() {
        return {
            post: null,
        }
    },

    mounted() {
        this.fetchPost();
    },

    methods: {
        fetchPost() {
            axios.get('/api/post/' + this.postId)
                 .then(response => this.post = response.data);
        },
    },
}
Run Code Online (Sandbox Code Playgroud)

请求完成后,EditPost有自己的副本可以进一步处理。

请注意,在每次编辑帖子和每次进入帖子列表时,您都会向服务器发出请求,这在某些情况下可能是不必要的,因为所有需要的信息已经在帖子列表中,并且在请求之间不会更改。如果您想在这种情况下提高性能,我建议将 Vuex 集成到您的应用程序中。如果您决定这样做,组件看起来会非常相似,只不过您不是通过 HTTP 请求获取帖子进行编辑,而是从 Vuex 存储中检索它。请参阅Vuex 文档以获取更多信息。