首页 新闻 赞助 找找看

Vue里 this.$router 不存在,怎么回事?

0
悬赏园豆:5 [已解决问题] 解决于 2022-12-17 10:51

以下是 vue 代码,我想在点击按钮事件中进行整体跳转(登录界面成功登录之后的整体界面变换),但是 this.$router.push("/main") 语句执行时,说 this.$router 不存在。在 chrome 里调试,断点在这里时,this 对象下有属性 $attrs、$data、$el…… 但确实是没有 $router 属性

<script>
import p1 from './components/Part1Comp.vue'
import p2 from './components/Part2Comp.vue'
import p3 from './components/Part3Comp.vue'
import NotFound from './components/NotFoundComp.vue'
import main from './components/MainComp.vue'

const routes = {
    '/goto-p1': p1,
    '/goto-p2': p2,
    '/goto-p3': p3,
  '/main': main
}

export default {
  data() {
    return {
      currentPath: window.location.hash
    }
  },
  computed: {
    currentView() {
      return routes[this.currentPath.slice(1) || '/'] || NotFound
    }
  },
  mounted() {
    window.addEventListener('hashchange', () => {
      this.currentPath = window.location.hash
    });
  },
  methods: {
    gotoMain() {
      this.$router.push("/main")
    }
  }
}
</script>

<template>
  <p>
  <a href='#/goto-p1'>第一部分</a> | 
  <a href='#/goto-p2'>第二部分</a> | 
  <a href='#/goto-p3'>第三部分</a> | 
  <button :onClick="gotoMain">进入主界面</button>
  </p>
  <component :is="currentView" />
</template>

 

 

背锅狼的主页 背锅狼 | 初学一级 | 园豆:60
提问于:2022-12-02 18:19
< >
分享
最佳答案
0

知道原因了,初始化时没有有选择路由功能

背锅狼 | 初学一级 |园豆:60 | 2022-12-17 10:51
其他回答(1)
0

试试

<button @click="gotoMain">进入主界面</button>

收获园豆:5
空明流光 | 园豆:106 (初学一级) | 2022-12-05 14:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册