gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:56:53 24 4
gpt4 key购买 nike

出于某种原因,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com