You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS中为何可在$router对象上调用数组push方法且生效?

Why can $router (VueRouter instance) call push method like an array?

Great question! Let's clear up this confusion right away: this.$router.push() has nothing to do with Array.prototype.push—they just happen to share the same method name, but are completely separate functions with different purposes.

Here's the breakdown:

  • When you create a VueRouter instance with new VueRouter(...) (like in your main.js), this instance inherits methods from the VueRouter class prototype. VueRouter defines its own push method specifically for route navigation, not array manipulation.
  • The $router.push() method's job is to add a new entry to the browser's history stack (using history.pushState in history mode, or updating the hash in hash mode) and trigger Vue to render the component matching the target route. This is how you navigate to a new page without a full page reload in Vue apps.
  • The array push method is for adding elements to the end of an array—totally unrelated functionality. The same method name is just a naming choice by the VueRouter team, not a sign that $router is an array.

To confirm with your code:

In your main.js, you create a router instance with new VueRouter({ routes, mode: 'history' }). This instance includes all the built-in navigation methods from VueRouter, including push. When you inject this router into your root Vue instance (new Vue({ router, ... })), Vue makes it available to all child components via this.$router—so calling this.$router.push({path: '/'}) in your user.vue component is invoking VueRouter's navigation method, not an array method.

If you're curious, VueRouter also provides other navigation methods like replace (replaces the current history entry instead of adding a new one) and go (navigates forward/backward in history), all of which are custom to the router instance.

内容的提问来源于stack exchange,提问作者dkjain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:08