一、两者的选择问题
注意:当要传的参数是通过v-model绑定页面中的表单而获取的时候,必须使用编程式路由导航,否则传参为空!
setup:
const planInfo = {
fromCity: "", //都是v-model绑定了页面的
backCity: "",
goDate: "",
};
错误传参方式:
<router-link
:to="{
name: 'TrvalPlan',
params: {
fromCity: planInfo.fromCity,
backCity: planInfo.backCity,
goDate: planInfo.goDate,
},
}"
target="_blank"
class="thm-btn tour-search-one__btn"
>
制定行程
</router-link>
正确的传参方式:
<button
@click="createPlan"
class="thm-btn tour-search-one__btn"
>
制定行程
</button>
const createPlan = () => {
router.push({
name: "TrvalPlan",
params: {
fromCity: planInfo.fromCity,
backCity: planInfo.backCity,
goDate: planInfo.goDate,
},
});
};
注意:在使用params传参时,必须使用命名式导航,即用name
二、使用参数的方法
1.用route接收并使用参数
注意:在router中useRoute和useRouter完全不一样,useRoute是用来接受参数的
在接受参数的页面中new route,然后使用params
//setup内:
const route = useRoute();
console.log(route.params.fromCity);
console.log(route.params);
2.使用props接收并使用参数
2.1 写法1
传参文件中:
const planInfo = {
fromCity: "",
backCity: "",
goDate: "",
};
const createPlan = () => {
router.push({
name: "TrvalPlan",
params: planInfo,
});
};
router配置文件中:
props: true,
接受参数的页面中:
props: ["fromCity", "backCity", "goDate"],
// 简单功能的实现
setup(props, context) {
console.log(props);
}
结果:
2.2 写法2
传参文件中:
const planInfo = {
fromCity: "",
backCity: "",
goDate: "",
};
const createPlan = () => {
router.push({
name: "TrvalPlan",
params: planInfo,
});
};
router配置文件中:
props(route) {
console.log("-------");
console.warn(route);
console.log("-------");
return {
fromCity: route.params.fromCity,
backCity: route.params.backCity,
goDate: route.params.goDate,
};
},
接受参数的页面中:
props: ["fromCity", "backCity", "goDate"],
// 简单功能的实现
setup(props, context) {
console.log(props);
}
结果:
2.3 写法3
传参文件中:
const planInfo = {
fromCity: "",
backCity: "",
goDate: "",
};
const createPlan = () => {
router.push({
name: "TrvalPlan",
params: planInfo,
});
};
router配置文件中:
props({ params: { fromCity, backCity, goDate } }) {
return {
fromCity,
backCity,
goDate,
};
},
接受参数的页面中:
props: ["fromCity", "backCity", "goDate"],
// 简单功能的实现
setup(props, context) {
console.log(props);
}
结果:
使用:直接用这三项即可!