以下是 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>
知道原因了,初始化时没有有选择路由功能
试试
<button @click="gotoMain">进入主界面</button>