VueRouter

安装路由模块

npm install vue-router

新建组件

首页组件

<template>
  <div id="homePage">
    首页
  </div>
</template>

<script>

var homePage = new Vue({
  el:"#homePage"
});

</script>

<style>
</style>

产品页面组件

<template>

  <div id="productPage">
      商品页面
    </div>

</template>

<script>
  var productPage = new Vue({
    el:"#productPage"
  });
</script>

<style>
</style>

创建静态路由表

router 目录下编辑 index.js 文件

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
// 引入组件
import Home from '../components/Home.vue'
import Product from '../components/Product.vue'


Vue.use(Router)

// 配置路径
export default new Router({
  routes: [
    {
      path: '/',
      component: HelloWorld
    },
    {
      path:'/home',    
      component:Home
    },
    {
      path:'/product',    
      component:Product
    }
  ]
})

无参调用

编辑 App.vue 文件 :

<template>
  <div id="app">
    <ul>
      <!--声明式调用-->
      <li><router-link to="/home">首页</router-link></li>
      <li><router-link to="/product">商品</router-link></li>
    </ul>
    <!--编程式调用-->
    <button @click='toPage("/home")'>首页</button>
    <button @click='toPage("/product")'>商品页</button>

    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods:{
    toPage:function(path){
      this.$router.push(path);
    }
  }
}
</script>

<style>

</style>

传参调用

通过 query 传递参数

在父组件中,通过路由属性 name 来确定匹配的路由,通过 **query ** 来传递参数:

export default {
  name: 'App',
  methods:{
    toPage:function(path){
      let id = 1111;
       // $router 是路由对象  
      this.$router.push({name:"Product",query:{id:id}});      
    }
  }
}

在子组件中,通过 query 来接收参数:

export default {
    data:function(){
      return {
        // $route 是路由信息对象
        id:this.$route.query.id,
       }
    }
}

在路由路径中也需要指定 name 属性:

export default new Router({
  routes: [
	......
    {
      path:'/product',
      name:'Product',
      component:Product
    }
  ]
})

通过 Params 传递参数

在父组件中,通过路由属性 name 来确定匹配的路由,通过 params 来传递参数:

export default {
  name: 'App',
  methods:{
    toPage:function(path){
      let id = 1111;
      this.$router.push({name:"Product",params:{id:id}});
    }
  }
}

在路由路径中需要指定 name 属性:

export default new Router({
  routes: [
	......
    {
      path:'/product',
      name:'Product',
      component:Product
    }
  ]
})

注:如果在 path 指定参数(如: path:'/product/:id',)的话,会在 URL上体现数据,反之不体现。

原文地址:https://www.cnblogs.com/markLogZhu/p/14265836.html