vue-rouuter编程式导航$router

    科技2024-11-17  14

    App.vue

    <template> <div id="app"> <div id="nav"> <router-link :to="{name:'Home'}">Home</router-link> | <router-link to="/about">About</router-link> <button @click="handelJsNavigation" v-show="showButton">编程式的导航</button> </div> <router-view></router-view> <router-view name="aView"></router-view> <router-view name="bView"></router-view> </div> </template> <script> export default { data() { return { showButton: true } }, methods: { handelJsNavigation() { this.showButton = false; /* 1、除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。 2、想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击 浏览器后退按钮时,则回到之前的 URL。 3、api如下 router.push(location, onComplete?, onAbort?) router.replace(location, onComplete?, onAbort?) router.go(n) 4、push第一个参数可以是path字符串也可以是对象 */ // this.$router.push("/test/123"); this.$router.push({name:"Test", params: { id: '123' }}); } }, } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>

    router/index.js

    import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Test from '../views/Test.vue' import NotFound from '../views/NotFound.vue' import TestChild from '../views/TestChild.vue' import AView from '../views/AView.vue' import BView from '../views/BView.vue' Vue.use(VueRouter) const routes = [ { path: '/', alias:'/home', name:'Home', components:{ default: Home, aView: AView, bView: BView, }, }, { path: '/test/:id', name: 'Test', component: Test, props:true, children:[ { path: ':name', name: 'TestChild', component: TestChild, props:true, meta:{ isRequiresAuth:true, isChecked:false, } }] }, { path: '/about', name: 'About', component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '*', name: 'NotFound', component: NotFound }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router

     

    Processed: 0.030, SQL: 8