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

 

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 @οnclick="pushtest" href="">Go to Bar</a>' }
// const Bar = { template: '<div @οnclick="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会向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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值