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

标签 javascript vue.js

出于某种原因,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();
    },
});

我在 SO 上看到了很多关于此问题的问题,但每次问题似乎都在于他们使用了箭头表示法。

就我而言,当我执行 console.log(this) 时,打印的对象中根本没有 $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();
    },
}); 

请参阅sample code here一个完整的例子。从上面的页面:

By injecting the router, we get access to it as this.$router as well as the current route as this.$route inside of any component

编辑:

为了清楚起见,粘贴上面链接中的一些示例代码。请注意注释中的步骤 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')

关于javascript - VueJS 中 this.$route 未定义(不使用箭头),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914827/

相关文章:

css - 如何设置vuetify卡的高度

angular - SPA 中的 Google DFP(Angular、Vue)——如何销毁广告及其所有引用以避免内存泄漏

javascript - 删除所有以 'font-' 开头的内联样式属性

javascript - 如何在 ES6 模板字符串中使用颜色?

php - 放入正文

javascript - Vue Router - 从 beforeEach 内部传递数据

javascript - 单元测试包含带有插槽的 Vuetify 数据表的 Vue 组件

javascript - 如何将 ISO 8601 转换为美国时区

javascript - Ctr + 单击在 ie11 中不起作用

javascript - 获取jade的正则表达式包括