你知不知之vue自定义路由和传参的故事(有示例代码)

router路由定义:index.js

import Vue from 'vue'
import Router from 'vue-router'
import Map from '@/components/Map'
import BaiDuMap from '@/components/BaiDuMap'

Vue.use(Router)

export default new Router({
    
    
  routes: [
	   {
    
    
	      path: '/Map',
	      name: 'Map',
	      component: Map
	    },
		{
    
    
			path: '/BaiDuMap',
			name: 'BaiDuMap',    //注意params需要这个属性name,是根据这个name进行跳转的
			component: BaiDuMap 
		}
	]
})

页面Map.vue =>BaiDuMap.vue

<template>
	<div class="amap-page-container">
	    <p @click="hah">看得到路由携带的参数</p>
	    <p @click="hi">看不到路由携带的参数</p>
	</div>
</template>

<script>
export default {
    
    
  data () {
    
    
    return {
    
    }
  },
  methods: {
    
    
 	hah () {
    
    
      // 以下两种方式都是一样的
      // this.$router.push({
    
    
      //   path: '/BaiDuMap?name=王大锤'
      // })
      this.$router.push({
    
    
        path: '/BaiDuMap',
        query: {
    
    
          name: '哈哈哈'
        }
      })
    },
    hi () {
    
    
      this.$router.push({
    
    
        name: 'BaiDuMap',
        params: {
    
    
          name: '王小锤'
        }
      })
    }
  }
}
</script>

触发hah方法(query)
在这里插入图片描述
触发hi方法(params)
在这里插入图片描述
BaiDuMap.vue接受参数(前面是query,后面是params)

this.$route.query.name

this.$route.params.name

<template>
  <div>
    {
    
    {
    
    this.$route.query.name+'--------'+this.$route.params.name}}
  </div>
</template>
<script>
export default {
    
    
  // name: 'BaiDuMap',
  data () {
    
    
    return {
    
    }
  }
}
</script>

用哪个主要取决于你是否需要隐藏参数,都可以用的。有什么不会欢迎留言。

猜你喜欢

转载自blog.csdn.net/qq_42899245/article/details/108102409