路由

70 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情

一。 初始路由

image.png

image.png

  1. 安装

    npm install vue-router
    
  2. 导入(在src目录下创建一个router文件,文件里创建index.js,配置卸载index.js里面)

     import Vue from 'vue'   (引入vue)
     import VueRouter from 'vue-router'    (引入路由)
     Vue.use(VueRouter)             (使用路由)
    
  3. 创建路由器

              // 导入页面组件
          import Index from '../pages/Index.vue'
          // 创建一个路由器对象
        export default new VueRouter({
        //定义当前路由器对象管理的路由信息
            routes:[{
               //路由路径
               path:'/',
               // *用于匹配所有没有匹配的路径
                path: "*",
             //路由名称
              name:'Index'
              //路由组件
               component:Index
             }]
          })
    
  4. 配置路由器(在main.js里面操作)

         // 导入当前项目中创建的路由器对象
          import router from './router'
           new Vue({
                 render: h => h(App),
             // 在Vue的实例上,配置一个路由器对象
                router
            }).$mount('#app')
    
  5. 使用路由

① 路由组件跳转

         <!-- 路由链接,用于跳转路由,to属性设置路由路径 -->
           <router-link to="/">首页</router-link>
        <!-- 路由视图,用于显示路由组件,当浏览器的地址栏中切换到指定的路由路径时,
        就会在router-view中显示对应的路由组件。-->
         <router-view></router-view>

(1)params传参

            <template>
               <div class="header">
<!-- params方式传参 -->
<h2>城市列表</h2>
<div><router-link to="/city/1">成都</router-link></div>
<div><router-link to="/city/2">南京</router-link></div>
<div><router-link to="/city/3">武汉</router-link></div>
             </div>
          </template>

        <script>
         export default {};
        </script>

      <style scoped>
      .header {
         border: 1px solid green;
           margin: 0 10px;
           padding: 0 10px;
            }
       .header a {
   /* color: black; */
        text-decoration: none;
        }
    .header div {
        margin: 5px 0;
     }
      </style>
      
      
      
        <template>
       <div class="top">
     <div v-for="(item, index) in full" :key="item.id">
      <p>{{ item.name }}</p>
    <p>{{ item.content }}</p>
    <p>
    <img :src="item.img" alt="" />
    </p>
   </div>
  </div>
 </template>

     <script>
     export default {
       props: ["id"],  //接受传参需要在index.js里的routes配置props:true
       data() {
           return {
         citys: [
        {
      id: "1",
      name: "成都",
      content:
        "成都,四川省辖地级市,简称“蓉”,别称蓉城、锦城,为四川省省会、副省级市 [183]  、超大城市 [173]  、国家中心城市 [217]  [251-252]  、成渝地区双城经济圈核心城市,国务院批复确定的国家重要的高新技术产业基地、商贸物流中心和综合交通枢纽、西部地区重要的中心城市 [1]  [206-207]  。",
      img: "https://img1.baidu.com/it/u=2874806358,1921281699&fm=253&fmt=auto&app=138&f=JPEG?w=650&h=434",
    },
    {
      id: "2",
      name: "南京",
      content:
        "南京,简称“宁”,古称金陵、建康 [1]  ,江苏省辖地级市、省会、副省级市、特大城市、南京都市圈核心城市, [2]  国务院批复确定的中国东部地区重要的中心城市、全国重要的科研教育基地和综合交通枢纽。",
      img: "https://img2.baidu.com/it/u=4066997595,1569431847&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=428",
    },
    {
      id: "3",
      name: "武汉",
      content:
        "武汉,简称“汉”,别称江城,是湖北省省会,中部六省唯一的副省级市及超大城市 [239-240]  ,中国中部地区的中心城市,全国重要的工业基地、科教基地和综合交通枢纽,联勤保障部队机关驻地",
      img: "https://img1.baidu.com/it/u=2612124584,2394899468&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
    },
  ],
  city: {},
  citysa: [],
};
},
 mounted() {
console.log(this.$route);
// 通过开启开启prop接受路由参数返回id
console.log(this.id);
},
  computed: {
  full() {
//   return this.citys.filter((r) => r.id == this.$route.params.id);

     return this.citys.filter((r) => r.id == this.id);

  
},
},

// 监视属性 // watch: { // $route: { // immediate: true, //立即开启监测 // handler() { // this.citya = this.citys.filter((r) => r.id == this.id); // console.log(this.citya);

 //   this.city = this.citys.find((r) => r.id == this.id);
  //    find返回的是符合条件的对象
//       },
//     },
//   },
};
</script>

 <style scoped>
 img {
 width: 580px;
 }
 .top {
 margin: 0 10px;
  }
 </style>

image.png

image.png

(2)query方式传参

           <template>
       <div class="header">
   <!-- query方式传参 -->
<h2>汽车列表</h2>
<div><router-link to="/car?id=1">宝马</router-link></div>
<div><router-link to="/car?id=2">奔驰</router-link></div>
<div><router-link to="/car?id=3">奥迪</router-link></div>
 </div>
   </template>

<script>
   export default {};
 </script>

  <style scoped>
  .header {
 border: 1px solid green;
  margin: 0 10px;
  padding: 0 10px;
 }
  .header a {
  /* color: black; */
  text-decoration: none;
}
 .header div {
 margin: 5px 0;
}
</style>


               <template>
   <div class="car">
<p>{{ car.name }}</p>
<p>{{ car.content }}</p>
<p><img :src="car.img" alt="" /></p>
  </div>
 </template>

 <script>
   export default {
   data() {
  return {
  cars: [
    {
      id: 1,
      name: "宝马",
      content:
        "宝马(BMW),中文全称为巴伐利亚发动机制造厂股份有限公司,德国汽车品牌,宝马的车系有i、X、Z、纯数字4个车型,1、2、3、4、5、6、7、8等几个系列,还有在各系基础上进行改进的M系(宝马官方的高性能改装部门",
      img: "https://img0.baidu.com/it/u=451728691,2819385667&fm=253&fmt=auto&app=120&f=JPEG?w=730&h=411",
    },
    {
      id: 2,
      name: "奔驰",
      content:
        "梅赛德斯-奔驰(Mercedes-Benz)是世界闻名的豪华汽车品牌。1886年1月,卡尔·本茨发明了世界上第一辆三轮汽车,获得专利(专利号:DRP 37435 [1]  ),被誉为“汽车的发明者”。",
      img: "https://img2.baidu.com/it/u=1524329523,720011713&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=800",
    },
    {
      id: 3,
      name: "奥迪",
      content:
        "奥迪(Audi),德国豪华汽车品牌,其标志为四个圆环相扣。现为德国大众汽车公司的子公司。2018年12月20日,2018世界品牌500强排行榜发布,奥迪位列51位。 [2]  2019年10月,Interbrand发布的全球品牌百强榜排名42。 [3] ",
      img: " https://img0.baidu.com/it/u=1608925924,3588736998&fm=253&fmt=auto&app=138&f=JPEG?w=680&h=434,",
    },
  ],
  car: {},
};
 },
  watch: {
  $route: {
  immediate: true,
  handler() {
    this.car = this.cars.find((r) => r.id == this.$route.query.id);
  },
},
  },
  };
 </script>

<style>
 img {
 width: 580px;
  }
 </style>
 
 

image.png

App组件

           <template>
   <div id="app">
<div class="nav">
  <router-link to="/">首页</router-link>
  <router-link to="/list">列表</router-link>
  <router-link to="">关于</router-link>

   <button @click="gohome">首页</button>
  <button @click="golist">列表</button>
  <button @click="goabout">关于</button>|
  <router-link to="/city/1">成都</router-link>
  <router-link to="/city/2">南京</router-link>
  <router-link to="/city/3">武汉</router-link>
</div>


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


  <script>
   export default {
   name: "App",
  components: {},
    methods: {
gohome() {
  console.log(this.$router);
  // $router返回当前项目中路由器对象
  if (this.$route.path != "/") {
    this.$router.push("/");
  }
},
golist() {
  // $route  返回的是当前路由信息
  console.log(this.$route);
  if (this.$route.path != "/list") {
    this.$router.push("/list");
  }
},
goabout() {
  if (this.$route.path != "/about") {
    this.$router.push("/about");
  }
},
  },
 };
 </script>

   <style>
#app {
 border: 1px solid #ccc;
  width: 600px;
}
  .nav {
 border: 1px solid #ccc;
  margin: 10px;
}
 .nav a {
 margin-left: 10px;
  text-decoration: none;
  color: black;
}
</style>

Vue.config.js

           const { defineConfig } = require('@vue/cli-service')
   module.exports = defineConfig({
  transpileDependencies: true,
      lintOnSave:false,   //关闭语法检查
// 配置开发服务器
devServer: {
  // 配置端口号
  port: "8848",
  // 项目启动后立刻打开
  open: true,
  // 主机名
  host: "localhost",
},
// 这里面配置webpack的原生配置
configureWebpack: {
  // 解析
  resolve: {
    // 定义路径别名
    alias: {
      "@c":path.resolve(__dirname,"src/components"),
      "@v": path.resolve(__dirname,"src/pages")
    },
  },
},
 })

image.png

②。 编程式路由跳转

         // $router就是当前项目中的路由器对象,它的push方法,用于跳转路由
         // replace方法,也是用于跳转路由。
         // push方法是在浏览器的历史记录中,添加一个路由信息
         // replace方法是在浏览器的历史记录中,替换前一条路由信息