javascript vue.js this.$router 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46983742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:06:13  来源:igfitidea点击:

vue.js this.$router undefined

javascriptvue.jsvuejs2vue-router

提问by sudo

I am getting undefined for

我正在为

this.$router

这个.$路由器

undefined in App.vue and other components. I couldn't find a solution.

在 App.vue 和其他组件中未定义。我找不到解决办法。

here a part of my main.js

这是我的 main.js 的一部分

Vue.use(VueRouter);
Vue.use(VueResource);

const router = new VueRouter({
    routes: Routes,
    mode: 'history'
});

new Vue({
    el: '#app',
    render: h => h(App),
    router
});

and here my router.js which I am importing in main.js.

这里是我在 main.js 中导入的 router.js。

export default [
    {path: '/', component: Home, name: 'home'},
    {path: '/home', component: Home, name: 'home2'},
    {path: '/user/login', component: Login, name: 'userLogin'}
];

Thank you :)

谢谢 :)

Edit

编辑

I was using it in script tags like this,

我在这样的脚本标签中使用它,

<script>
    import HeadNavBar from './components/HeadNavBar.vue';
    import SideBarNav from './components/SideBarNav.vue';
    import Home from './components/Home.vue';


    console.log(this.$router,pus); //the undefined type

    export default {
        name: 'app',
        data() {
            return {
                isLogin: true
            }
        },
        components: {
            'app-headnav': HeadNavBar,
            'app-sidebarnav': SideBarNav,
            'app-home': Home
        }

    }
</script>

but when I moved it into the method section, I got the response I wanted.

但是当我把它移到方法部分时,我得到了我想要的回应。

export default {
    name: 'app',
    data() {
        return {
            isLogin: true
        }
    },
    components: {
        'app-headnav': HeadNavBar,
        'app-sidebarnav': SideBarNav,
        'app-home': Home
    },methods: {
        myFunc: function() {
            console.log(this.$router,pus); // this gave result
        }
    }
}

回答by tony19

I can only reproduce the undefinederror for this.$routerwhen using an arrow function(perhaps that's what you're doing), which the Vue documentationrecommends against:

我只能在使用箭头函数时重现undefined错误(也许这就是你正在做的事情),Vue 文档不建议这样做:this.$router

Don't use arrow functions on an options property or callback, such as created: () => console.log(this.a)or vm.$watch('a', newValue => this.myMethod()). Since arrow functions are bound to the parent context, thiswill not be the Vue instance as you'd expect, often resulting in errors such as Uncaught TypeError: Cannot read property of undefinedor Uncaught TypeError: this.myMethod is not a function.

不要在选项属性或回调上使用箭头函数,例如created: () => console.log(this.a)vm.$watch('a', newValue => this.myMethod())。由于箭头函数绑定到父上下文,this因此不会像您期望的那样是 Vue 实例,通常会导致诸如Uncaught TypeError: Cannot read property of undefined或 之类的错误Uncaught TypeError: this.myMethod is not a function

Here's an example of the mountedcallback logging this.$routersuccessfully:

以下是mounted回调日志this.$router成功的示例:

<script>
  export default {
    name: 'app',

    // DON'T USE ARROW FUNCTIONS HERE
    // mounted: () => {
    //   console.log({router: this.$router});
    // },

    mounted() {
      console.log({router: this.$router});
    }
  }
</script>

回答by Jason Ulwelling

I know this is old, but I am gonna share something I ran into and how I got around it in case someone is struggling out there.

我知道这是旧的,但我会分享我遇到的一些事情以及我如何解决它,以防有人在那里挣扎。

My scenario is a vue/meteor project.

我的场景是一个 vue/meteor 项目。

In functions/handlers, "this" refers to the function's target, so this.$router is looking for $router within the function or the target itself.

在函数/处理程序中,“this”指的是函数的目标,因此 this.$router 在函数内或目标本身中寻找 $router。

    ///////DOESN'T WORK ///////////
  mounted: function () {
    $(document).on('click', '.element', function(){
             //this is recognized as 
             this.$router.push(PATH)
        });
  },


    ////////THIS WORKS//////////
  mounted: function () { 
    //make router defined outside of function.
    var navigate = this.$router;

     $(document).on('click', '.element', function(){
        navigate.push(PATH)
     });
  }

回答by DRL

The console.log(this.$router,pus)above the exportis executed when import the component. It happened before the component was created. So thisis just a empty object {}.

console.log(this.$router,pus)上述export导入部件时被执行。它发生在组件创建之前。所以this只是一个空对象{}

You should get the this.$routerinside the methods of export object.

您应该了解this.$router导出对象的方法。

回答by Arian saputra

we have a same error, in this case i have fixed that, i just import the router files in my component like this and it's working:

我们有同样的错误,在这种情况下我已经解决了这个问题,我只是像这样在我的组件中导入路由器文件并且它正在工作:

import router files/configuration in my component :

在我的组件中导入路由器文件/配置:

import router from '../router'

and i can use that like this :

我可以像这样使用它:

router.replace('home')

and that's should be working

这应该有效

my full code :

我的完整代码:

<script>
import router from '../router'
export default {
  methods: {
  signIn: function () {
    firebase
    .auth().signInWithEmailAndPassword(this.email, this.password).then(
      function (user) {
        router.replace('home')
      },
      function (err) {
        alert('Maaf, ' + err.message)
      }
    )
  }
 }
}
</script>