簡體   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