VueRouter路由使用
小于 1 分钟
VueRouter路由使用
1.路由包含参数配置
1.1在定制请求中,定制参数
import httpInstance from "@/utils/http";
//category.js
export const getCategoryAPI = (id) => {
return httpInstance({
url: "/category",
params: {
id
}
})
}
1.2在组件中获取路由参数
1.引入 useRoute 对象
2.定义变量route
3.在请求接口中写入路由参数
<script setup>
import { getCategoryAPI } from "@/apis/category.js";
import { onMounted, ref } from "vue";
1.import { useRoute } from "vue-router";
2.const route = useRoute();
const categoryList = ref({});
const getCategory = async () => {
const res = await getCategoryAPI(3.route.params.id);
categoryList.value = res.result;
};
getCategory();
onMounted(() => {
getCategory();
});
</script>
2.一级路由配置
2.1路由配置中==>占位
{
path: "category/:id",
component: Category,
}
2.2 组件中
注意:
1.动态获取to前面要加 :
2.to里面的路径为字符串拼接使用 反引号(),且id是动态的变量需要用 ${}
<li
v-for="categorys in categoryStore.categoryList"
:key="categorys.id"
>
<RouterLink :to="`/category/${categorys.id}`">{{
categorys.name
}}</RouterLink>
</li>