之三 程式設計式路由
阿新 • • 發佈:2019-01-07
程式設計式路由,即通過寫js 函式,實現路由的跳轉。之前路由跳轉是通過router-link實現,本篇,我們通過函式來實現router-link 的跳轉功能。
舉例。
首先是router/index.js 程式碼,如下。
import Vue from 'vue' import Router from 'vue-router' import GoodList from '@/views/GoodList' import Title from '@/views/Title' import Image from '@/views/Image' import Cart from '@/views/Cart' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/goods', name: 'GoodList', component: GoodList, children: [ { path: 'title', name: 'Title', component: Title }, { path: 'image', name: 'Image', component: Image } ] }, { path: '/cart', name: 'Cart', component: Cart } ] })
然後是cart.vue 程式碼如下。
<template>
<div>
購物車
<span>{{$route.query.goodsId}}</span>
</div>
</template>
<script>
export default {
name: 'Cart'
}
</script>
最後是Goodlist.vue 程式碼如下。
<template> <div> 這是商品列表頁 <span>{{$route.params.goodsId}}</span> <br /> <span>{{$route.params.name}}</span> <router-link to="/goods/title">顯示商品標題</router-link> <router-link to="/goods/image">顯示商品圖片</router-link> <div> <router-view></router-view> </div> <router-link to="/cart">跳轉到購物車</router-link> <button @click="jump">button - 跳轉到購物車</button> </div> </template> <script> export default { name: 'GoodList', methods: { jump() { this.$router.push({path: '/cart?goodsId=123'}); // this.$router.push('/cart'); } } } </script> <style scoped> </style>
Done!