laravel + vue 路由器无法从 url 获取参数

laravel + vue router cannot get parameters from url

我尝试从 url

获取参数

假设 url 包含:

localhost:8000/blog?q=hello

我要抢hello触发函数调用

我在 laravel webpack 中的 app.js 中声明的内容:

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

const router = new VueRouter({
    mode: 'history',
    routes: []
})

const app = new Vue({
    router
});

export default app;

在博客页面中,我尝试从 url

中提取参数
new Vue ({
       el: "#blog-content",
   },

   mounted: function() {
       q = this.$route.query.q
       console.log(q)
   }
)

npm run dev编译并且运行博客页面显示错误:

TypeError: Cannot read property 'query' of undefined

怎么了?我确定 Vue Router 已正确安装在应用程序中。

我认为您使用的博客页面不正确。

您重新创建另一个 Vue 实例,在这种情况下,新实例没有传递给它的路由器。所以我认为这就是 this.$router 未定义的原因。

此外,您没有将视图组件传递给您的路由器,因此它不知道要查找特定的 url。

这是您的 app.js 更正文件

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

import Blog from './views/Blog';

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/blog',
            name: 'blog',
            component: Blog
        },
    ]
});

博客查看页面模板:views/Blog.vue

<template>
    <div class="wrapper">
         My blog page
    </div>
</template>


<script>
    export default {
        data() {
            return {
                myvariable : ''
            }
        },
        mounted() {
            let q = this.$route.query.q;
            console.log(q);
        },
    };
</script>

现在它应该可以正常工作了:)

编辑:您也不需要在 app.js

中导出 app 变量

删除文件末尾的以下行export default app;