vue 二级路由和路由传参

本文最后更新于2024.05.30-05:34,某些文章具有时效性,若有错误或已失效,请在下方留言或联系涛哥

1,param传参方式

nav.vue

<template>
  <div class="title">
				<span>热门标签</span>
				<span>点击即可查看本标签的内容</span>
				<ul>
					<li>
                        <router-link to="/alllabels" active-class="current">全部标签</router-link>
                    </li>
					<li>
                        <router-link to="/pepolelh" active-class="current">民生</router-link>
                    </li>
					<li>
                        <a href="">社会</a>
                    </li>
					<li>
                        <a href="">日常</a>
                    </li>
				</ul>
                <router-view></router-view>
			</div>
</template>

<script>
export default {
        name:'Navigation'

}
</script>

<style scoped>
        .title{
				width: 980px;
				height: 88px;
				background-color: #fff;
				margin: 0 auto;
			}
			.title span:nth-child(1){
						font-size: 18px;
						line-height: 24px;
						color: #222;
						vertical-align: middle;
					}
					.title span:nth-child(2){
						color: #99a2aa;
						margin-left: 20px;
						margin-bottom: 2px;
						display: inline-block;
						vertical-align: bottom;
					}
					.title ul{
						overflow: hidden;
						margin-right: -10px;
						list-style:none;
					}

					.title ul li{
						/* display: inline-block; */
						float: left;
						position: relative;
						border: 1px solid #e5e9ef;
						border-radius: 12px;
						background-color: #fff;
						height: 22px;
						margin: 5px 10px 5px 0;
						cursor: pointer;
					}

					.title ul li a{
						display: block;
						line-height: 22px;
						text-overflow: ellipsis;
						overflow: hidden;
						white-space: nowrap;
						color: #222;
						padding: 0 10px;
						text-decoration: none;
						font-size: 10px;
                        border-radius: 12px;
					}

					.current{
						background-color: #00a1d6!important;
					}

					.current a{
						color:#FFFFFF!important;
					}
</style>

AllLabels.vue

<template>
  <div class="content">
    <h1>这是全部标签组件</h1>
    <ul>
      <li v-for="(ss, index) in scenicSpot" :key="index">
        <router-link
          :to="{
            path: '/alllabels/info',
            name: 'info', //命名路由
            params: {//传递参数 
              
              sName: ss.sName,
              num: ss.num,
            },
			query:{//传递参数 通过get请求带参的方法
						pass:'123321'
					}
          }"
          >{{ ss.sName }}</router-link
        >
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "AllLabels",
  data() {
    return {
      scenicSpot: [
        { sName: "武侯祠", num: 20000 },
        { sName: "杜甫草堂", num: 18000 },
        { sName: "宽窄巷子", num: 22000 },
        { sName: "熊猫基地", num: 31000 },
      ],
    };
  },
};
</script>

<style scoped>
.content {
  width: 980px;
  height: 500px;
  margin: 0 auto;
  background-color: #fff;
}
.content h1 {
  text-align: center;
}
</style>

ScenicSpotInfo.vue

<template>
    <div>
        <h1>{{$route.params.sName}}景点的详细信息</h1>
        <h2>当前人数:{{$route.params.num}}</h2>
    </div>
</template>

<script>
export default {
    name:'ScenicSpotInfo',
    beforeUpdate(){//当组件加载之后
        // 1,拿到这个id
        console.log('id',this.$route.params.num);
        // 2,带着id去请求后端

        // 3,把后端的数据渲染在页面上

    }

}
</script>

<style>

</style>

路由配置

// 该文件专门用来创建和管理整个应用的路由器

import VueRouter from "vue-router";
import AllLabels from '../pages/AllLabels';
import PepolesLH from '../pages/PepolesLH';
import ScenicSpotInfo from '../pages/ScenicSpotInfo';

// 创建并暴露一个路由器
export default new VueRouter({
    // 地址和组件的对应关系
    routes:[
        {//一级路由才需要写‘/’,子路由不需要
            path:"/alllabels",//地址
            component:AllLabels,//组件
            children:[
                {
                    name:'info',//命名路由
                    path:"info/:sName/:num",//地址
                    component:ScenicSpotInfo, 
                }
            ]
        },
        {
            path:"/pepolelh",//地址
            component:PepolesLH//组件
        },
    ]
})

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
//上面的步骤等于<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
import App from './App'
//npm i vue-router
// 导入路由
import VueRouter from 'vue-router';
// 引入路由配置
import router from './router'
// vue使用路由插件
Vue.use(VueRouter);
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },//注册
  router:router,//new vue对象的时候装配在上面
  template: '<App/>'//在指定作用域添加模板标签

App.vue

<template>
  <div id="app">
    <Navigation/><br><br><br>
    

  </div>
</template>

<script>
//引入组件
import Navigation from './components/Navigation.vue'

export default {
  name: 'App',
  components: {//注册组件
    Navigation
  }
}
</script>

 2,query传参方式(基本和上面一样)

AllLabels.vue

<template>
    <div class="content">
		<h1>这是全部标签组件</h1>
		<ul>
			<li v-for="(ss,index) in scenicSpot" :key="index">
				<!-- <router-link to="/alllabels/info">{{ss.sName}}</router-link> -->
				<!-- 命名路由的对应写法 -->
				<!-- <router-link :to="{name:'info'}">{{ss.sName}}</router-link> -->
				<!-- 路由在切换的时候进行传值 -->
				<!-- <router-link :to="`/alllabels/info?sName=${ss.sName}&num=${ss.num}`">{{ss.sName}}</router-link> -->
				<!-- 传值的第二种写法 -->
				<router-link :to="{
					path:'/alllabels/info',
					name:'info',//命名路由
					query:{//传递参数
						sName:ss.sName,
						num:ss.num
					}
				}">{{ss.sName}}</router-link>
			</li>
		</ul>
		<router-view></router-view>
	</div>
</template>

<script>
export default {
    name:'AllLabels',
	data(){
		return{
			scenicSpot:[
				{sName:'武侯祠',num:20000},
				{sName:'杜甫草堂',num:18000},
				{sName:'宽窄巷子',num:22000},
				{sName:'熊猫基地',num:31000},
			]
		}
	}
}
</script>

<style scoped>
    .content{
		width: 980px;
		height: 500px;
		margin: 0 auto;
		background-color: #fff;
	}
	.content h1{
		text-align: center;
	}
</style>

3,还有一种方式直接在index.js文件里通过设置props传参

Navigation.vue

<template>
  <div class="title">
    <span>热门标签</span>
    <span>点击即可查看本区标签的相关内容</span>
    <ul>
      <!-- active-class 被激活的样式 -->
      <li>
        <router-link to="/dianshiju" active-class="current"
          >电视剧</router-link
        >
      </li>
      <li>
        <router-link to="/dianying" active-class="current">电影</router-link>
        <!-- <a href="#/peopleslh">民生</a> -->
      </li>
      <li>
        <router-link to="/zongyi" active-class="current"
          >综艺</router-link
        >
      </li>
      <li>
        <router-link to="/dongman" active-class="current">动漫</router-link>
        <!-- <a href="#/peopleslh">民生</a> -->
      </li>
      <li @click="back">后退</li>
      <li @click="forward">前进</li>
      <li @click="backOrForward">回退/前进</li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
//最终转换为a标签默认push可以加上replace
//
export default {
  name: "Navigation",
  methods: {
    JumpToAll() {
      this.$router.push({
        name: "sinfo", //命名路由
        params: {
          //传递参数
          temp: "all",
        },
      });
    },
    back(){
        this.$router.back()
    },
    forward(){
        this.$router.back()
    },
    backOrForward(){
        // 负数代表后退几步 
        // 整数代表前进几步 
        // 0 刷新页面
        this.$routerrouter.go(-3);
    }

  },
};
</script>

<style scoped>
.title {
  width: 980px;
  height: 88px;
  background-color: #fff;
  margin: 0 auto;
}
.title span:nth-child(1) {
  font-size: 18px;
  line-height: 24px;
  color: #222;
  vertical-align: middle;
}
.title span:nth-child(2) {
  color: #99a2aa;
  margin-left: 20px;
  margin-bottom: 2px;
  display: inline-block;
  vertical-align: bottom;
}
.title ul {
  overflow: hidden;
  margin-right: -10px;
  list-style: none;
}
.title ul li {
  /* display: inline-block; */
  float: left;
  position: relative;
  border: 1px solid #e5e9ef;
  border-radius: 12px;
  background-color: #fff;
  height: 22px;
  margin: 5px 10px 5px 0;
  cursor: pointer;
}
.title ul li a {
  display: block;
  line-height: 22px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  color: #222;
  padding: 0 10px;
  text-decoration: none;
  font-size: 10px;
}
.current {
  background-color: #00a1d6 !important;
}
.current a {
  color: #ffffff !important;
}
</style>

ScenicSpotInfo.vue

<template>
  <div>
      <h1>{{sName}}景点的详细信息</h1>
      <h1>当前人数:{{num}}</h1>
      <h1>{{a}}</h1>
  </div>
</template>

<script>
export default {
    name:'ScenicSpotInfo',
    props:["sName","num","a"],
    mounted(){//第一次加载
        this.getPageData();
    },
    watch:{//监听
        '$route'(){//监听路由
            this.getPageData();
        }
    },
    methods:{
        getPageData(){//自定义的方法
            console.log("获取到id",this.num);
            //请求后端渲染页面
        }
    }
}
</script>

<style>

</style>

路由配置 index.js

//该文件专门用来创建和管理整个应用的路由器
import VueRouter from "vue-router"
import AllLabels from "../pages/AllLabels"
import PeoplesLH from "../pages/PeoplesLH"
import ScenicSpotInfo from "../pages/ScenicSpotInfo"

//创建并暴露一个路由器
export default new VueRouter({
    //地址和组件的对应关系
    routes:[
        {
            path:'/dianshiju',//地址
            name:'dianshiju',
            component:AllLabels,//组件
            children:[
                {//一级路由才需要斜杠 子路由不需要斜杠
                    name:'info',//命名路由
                    path:'info',//地址
                    component:ScenicSpotInfo,//组件
                    //第一种 坏处:数据写死了  好处:可以自定义数据
                    //props:{sName:"故宫",num:100000000,a:123}
                    //第二种 如果为true就会把所有的params以props的形式传递给组件
                    //props:true
                    //第三种 以函数的形式传递
                    props({params}){
                        return{
                           temp:params.temp
                        }
                    }
                }
            ]
        },
        {
            path:'/peopleslh',//地址
            component:PeoplesLH//组件
        }
    ]
})
阅读剩余
THE END