VueJS中为何可在$router对象上调用数组push方法且生效?
$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 yourmain.js), this instance inherits methods from theVueRouterclass prototype. VueRouter defines its ownpushmethod 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 (usinghistory.pushStatein 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
pushmethod 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$routeris 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

