简体   繁体   English

vue.js this.$router 未定义

[英]vue.js this.$router undefined

I am getting undefined for我越来越不确定

this.$router这个.$路由器

undefined in App.vue and other components.在 App.vue 和其他组件中未定义。 I couldn't find a solution.我找不到解决方案。

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
        }
    }
}

I can only reproduce the undefined error for this.$router when using an arrow function (perhaps that's what you're doing), which the Vue documentation recommends against:我只能在使用箭头函数(也许这就是你正在做的事情)时重现this.$routerundefined错误, Vue 文档建议不要这样做:

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()) .不要在选项属性或回调上使用箭头函数,例如created: () => console.log(this.a)vm.$watch('a', newValue => this.myMethod()) Since arrow functions are bound to the parent context, this will not be the Vue instance as you'd expect, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function .由于箭头函数绑定到父上下文, this不会是您期望的 Vue 实例,通常会导致诸如Uncaught TypeError: Cannot read property of undefinedUncaught TypeError: this.myMethod is not a function

Here's an example of the mounted callback logging this.$router successfully:这是一个成功记录this.$routermounted回调示例:

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

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

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

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)
     });
  }

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>

The console.log(this.$router,pus) above the export is executed when import the component. export上面的console.log(this.$router,pus)是在导入组件时执行的。 It happened before the component was created.它发生在组件创建之前。 So this is just a empty object {} .所以this只是一个空对象{}

You should get the this.$router inside the methods of export object.您应该在导出对象的方法中获取this.$router

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

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