繁体   English   中英

this.$route 在 VueJS 中未定义(不使用箭头)

[英]this.$route undefined in VueJS (without using arrows)

出于某种原因, this.$route对我来说是未定义的。 我刚刚开始构建我的 Vue 应用程序:

window.Vue = require('vue');

new Vue({
    el : '#break-container',
    data : {
        break : null
    },
    methods : {
        fetchBreak : function(){
            console.log(this.$route);    //undefined
        },
    },
    mounted : function(){
        this.fetchBreak();
    },
});

我看到一堆关于这个的问题,但每次问题似乎都是他们使用箭头符号。

就我而言,当我执行 console.log(this) 时,打印的 object 中根本没有 $route 键。 键( $attrs, $children, ... , $vnode, break )。

我能做些什么来解决这个问题?

据我了解,如果您在创建 Vue 应用程序时注册路由器,则this.$route仅在 Vue 实例上可用。 您的代码似乎缺少路由器定义和 Vue 实例上的后续初始化

new Vue({
    el : '#break-container',
    // Register your router
    router: router,
    data : {    
        break : null   
    },
    methods : {
        fetchBreak : function(){
            console.log(this.$route);    //undefined
        },
    },
    mounted : function(){
        this.fetchBreak();
    },
}); 

有关完整示例,请参见此处的示例代码 从上面的页面:

通过注入路由器,我们可以访问它作为 this.$router 以及当前路由作为 this.$route 在任何组件内部

编辑:

为了清楚起见,粘贴上面链接中的一些示例代码。 请注意评论中的步骤 0-4。 奇怪的是,您的代码中缺少其中一个步骤:)

// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.

// 1. Define route components.
// These can be imported from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
  routes // short for `routes: routes`
})

// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
  router
}).$mount('#app')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM