0
点赞
收藏
分享

微信扫一扫

vue 路由传参

大沈投资笔记 2022-03-12 阅读 88

 

(2)路由传参

 ①query传参

  

this.$router.push({name:'home',query: {id:'1'}})

this.$router.push({path:'/home',query: {id:'1'}})

// html 取参  $route.query.id

// script 取参  this.$route.query.id

 ②params传参

this.$router.push({name:'home',params: {id:'1'}})  // 只能用 name

// 路由配置 path: "/home/:id" 或者 path: "/home:id" ,

// 不配置path ,第一次可请求,刷新页面id会消失

// 配置path,刷新页面id会保留

  

// html 取参  $route.params.id

// script 取参  this.$route.params.id

 ③query和params区别

query类似 get, 跳转之后页面 url后面会拼接参数,类似?id=1, 非重要性的可以这样传, 密码之类还是用params,刷新页面id还在

  params类似 post, 跳转之后页面 url后面不会拼接参数 , 但是刷新页面id 会消失

3.router-link和router.push实现跳转的原理

router-link

默认会渲染为 a 标签. 可以通过 tag 属性修改为其他标签 自动为 a 标签添加 click 事件. 然后执行 $router.push() 实现跳转

$router.push 根据路由配置的 mode 确定使用 HTML5History 还是 HashHistory 实现跳转  

HTML5History : 调用   window.history.pushState() 跳转

HashHistory : 调用  HashHistory.push() 跳转

那么二者到底有什么区别呢?

mode:'hash' ,   多了 “ # ”

http://localhost:8080/#/hello

mode:'history'

http://localhost:8080/hello

router index.js


{
// 参数 用 : 代表, ?代表可选
path: '/product/:type?',
props: true,
name: 'Product',
component: () => import('../views/Product.vue'),
},
              <router-link

:class="{ 顶部导航 当前路由高亮
'router-link-exact-active': $route.name == 'Product',
}"

to="/product"
>
产品中心<span class="icon_pd"></span
></router-link>
<div class="pd_dropdown">
<router-link to="/product/1">净美仕净化器</router-link>
<router-link to="/product/2">净美仕滤网</router-link>
</div>

    <div class="main container">
<div class="pl_header">
下边路由高亮
<router-link to="/product/1" :class="{ cur: type == 1 }"
>
净美仕净化器</router-link
>
<router-link to="/product/2" :class="{ cur: type == 2 }"
>
净美仕滤网</router-link
>
</div>
export default {
computed: {
...mapState(["imgURL"]),
},
// 属性的复杂写法: 可以声明默认值, 应对可选传参
// props: ['type'], //简化写法
props: {
// 属性名:{详细的配置}
type: {
// 通过路径传递的参数, 都是字符串类型
type: String, //类型: String是数字类型
default: "1", //默认值: '1', 如果没传, 则默认是1
},
},
mounted() {
this.getData();
},
data() {
return {
data: null,
};
},
methods: {
getData(page = 1) {
// type: 可选传递, 没有传递则为 undefined, 默认值为1
// 因为 在props中, 指定了默认值, 所以此处不需要再判断
// const type = this.type ?? 1 // ?? 左侧值是false 则用右侧值
const url = `product_select.php?pageNum=${page}${this.type}`;

this.axios.get(url).then((res) => {
console.log(res);
this.data = res.data;
});
},
},
// 监听到路由变化时, 重新发请求
watch: {
$route(newValue, oldValue) {
this.getData();
},
},
};
举报

相关推荐

0 条评论