How to use push, go, replace functions in vue components!

Using the `push`, `go` and `replace` functions in Vue.js requires a dependency on the Vue Router library, which is the official routing manager for Vue.js. The following will show you how to use these functions in Vue components:

1. First, make sure your project has Vue Router installed. If it is not installed, it can be installed via npm or yarn:

```bash
npm install vue-router
# or
yarn add vue-router
```

2. Create and configure a Vue Router instance. In your project, there will generally be a `router/index.js` file for configuring routing:

```js
// router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  // Define your routes here
  // For example:
  // { path: '/', component: Home },
  // { path: '/about', component: About },
];

const router = new VueRouter({
  mode: 'history', // Choose between 'hash' and 'history' mode for URL formatting
  routes,
});

export default router;
```

3. In the root Vue instance, inject the above Vue Router instance to make the routing manager take effect:

```js
// main.js

import Vue from 'vue';
import App from './App.vue';
import router from './router'; // Import the router instance created in the previous step

new Vue({
  router, // Inject the router instance into the Vue instance
  render: h => h(App),
}).$mount('#app');
```

4. Use `push`, `go` and `replace` functions in components. Now that you have Vue Router configured, you can use these functions in your components for route navigation:

```vue
<template>
  <div>
    <!-- Example button to trigger the navigation functions -->
    <button @click="goToHome">Go to Home</button>
    <button @click="goToAbout">Go to About</button>
    <button @click="goBack">Go Back</button>
    <button @click="replacePage">Replace Page</button>
  </div>
</template>

<script>
export default {
  methods: {
    goToHome() {
      // Using push to navigate to the '/home' route
      this.$router.push('/home');
    },
    goToAbout() {
      // Using push to navigate to the '/about' route
      this.$router.push('/about');
    },
    goBack() {
      // Using go to navigate one step back in the history stack
      this.$router.go(-1);
    },
    replacePage() {
      // Using replace to navigate to a new route, replacing the current one in the history stack
      this.$router.replace('/new-page');
    },
  },
};
</script>
```

Please modify the routing path and component name according to your project routing configuration and component structure. In this way, when the button is clicked, your Vue component will use `push`, `go` and `replace` functions for navigation and routing jumps.

おすすめ

転載: blog.csdn.net/qq_58647634/article/details/131840779