【问题标题】:laravel + vue router cannot get parameters from urllaravel + vue 路由器无法从 url 获取参数
【发布时间】:2019-08-11 23:04:34
【问题描述】:

我尝试从 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 已正确安装在应用程序中。

【问题讨论】:

    标签: laravel-5 vue-router


    【解决方案1】:

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

    您重新创建另一个 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;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-03
      • 2020-09-09
      • 2019-08-15
      • 1970-01-01
      • 2021-05-23
      • 2019-02-08
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多