【问题标题】:VueJS Router: $route is not definedVueJS 路由器:$route 未定义
【发布时间】:2018-07-05 07:09:10
【问题描述】:

这是我的组件:

const Vue = require("vue/dist/vue.js");
const qs = require("querystring");

module.exports = Vue.component("Page",function(resolve){
    console.log($route);
    let id = this.$route.params.id;
    fetch("/getPage.json",{
        method:"POST",
        body:qs.stringify({
            id
        })
    }).then(r=>r.json())
    .then(j=>{
        console.log(j);
        resolve({
            template:`<h1>`+JSON.stringify(j)+"</h1>"
        });
    })
});

这是我的路由器:

const router = new VueRouter({
	mode:"history",
	routes:[
		{
			path:"/",
			component:Home
		},
		{
			path:"/me",
			component:Me
		},
		{
			path:"/create-page",
			component:createPage
		},
		{
			path:"/p/:id",
			component:Page
		}
	]
});
Vue.use(VueRouter);

当我运行这个应用程序时,我得到:

ReferenceError: $route is not defined

我尝试使用this.$route,但它不起作用。我正在使用箭头功能。当我这样做时,它会起作用:

const Vue = require("vue/dist/vue.js");

module.exports = Vue.component("Page",function(resolve){
  resolve({
    template:`<h1>{{$route.params.id}}`
  });
});

请帮我弄清楚如何解决这个问题。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    在你的主 vue 应用中

    new Vue(...)
    

    你必须先使用 vue-router

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

    然后继续声明路由

    【讨论】:

    • 我正在使用Vue.use(VueRouter)
    【解决方案2】:

    您忘记在Vue 实例中添加router

    在你的 main.js 或 app.js 或 index.js(入口点)

    const app = new Vue({
      router
    })
    

    documentation

    【讨论】:

      【解决方案3】:

      你不应该使用箭头函数

      data: function() {
          return {
            usertype: this.$route.params.type
          };
        },
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 2018-08-20
        • 2015-10-17
        • 2021-01-30
        • 2022-10-14
        • 2021-11-24
        • 1970-01-01
        • 2019-10-05
        • 2016-02-06
        • 1970-01-01
        相关资源
        最近更新 更多