vue路由--使用router.push进行路由跳转

手机赚钱怎么赚,给大家推荐一个手机赚钱APP汇总平台:手指乐(http://www.szhile.com/),辛苦搬砖之余用闲余时间动动手指,就可以日赚数百元

  • route-link是在html中静态定义的,也可以在代码中动态跳转:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>abc</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello App!</h1>
        <!-- 路由出口 -->
        <!-- 路由匹配到的组件将渲染在这里 -->
        <router-view>
        </router-view>
    </div>
</body>
<script type="text/javascript">
// 0. 如果使用模块化机制编程,导入 Vue 和 VueRouter,要调用 Vue.use(VueRouter)

// 1. 定义(路由)组件。
// 可以从其他文件 import 进来
// const Foo = { template: '<div @onclick="pushtest" href="">Go to Bar</a>' }
// const Bar = { template: '<div @onclick="pushtest" href="">Go to Foo</a>' }

const Foo = Vue.extend({
    template: '<a @click="pushtest" href="javascript:void(0)">Navigate to bar</a>',
    methods: {
        pushtest() {
            //alert("bar");
            this.$router.push({ name: 'bar' });
            //alert("fdas");
        },
    },

});

const Bar = Vue.extend({
    template: '<a @click="pushtest" href="javascript:void(0)">Navigate to foo</a>',
    methods: {
        pushtest() {
            //alert("foo");
            this.$router.push({ name: 'foo' });
            //alert("fdas");
        },
    },
});

// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
    { path: '/', redirect: "/bar" },
    { path: '/foo', name: "foo", component: Foo },
    { path: '/bar', name: "bar", component: Bar },

]

// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
    routes // (缩写)相当于 routes: routes
})

// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
    router, // (缩写)相当于 router: router
    //  methods: {
    //     pushtest:function() {
    //         alert("fdas");
    //     },
    // },
    watch: {
        $route(to, from) {
            //alert(to.path);
            //document.getElementById("testzy").innerText = this.$route.params.id;
        }
    },

}).$mount('#app') // 现在,应用已经启动了!
</script>

</html>

 注意绝对不能写href="",这样执行click跳转后,又会执行href跳转到当前页面

push也可以直接使用path:

this.$router.push('/foo');
  • push会向history添加一条新记录,此时后退会跳转到前一个组件

router.replace(location)跟push功能类似,但是不会向history添加一条新记录,不能后退

router.go(n)

这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)。

 
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
原文地址:https://www.cnblogs.com/cowboybusy/p/9517378.html