VueRouter路由使用
2024年11月17日大约 1 分钟
VueRouter路由使用
1.VueRouter配置
安装路由器vue-router报错
常见问题:注意vue版本---与vue-router对应关系
安装指令:
@符为安装指定版本,没有@默认安装最新版
npm install --save vue-router@3
vue2项目中要使用vue-router3版本,要用vuex3 的版本
vue3项目中要使用vue-router4版本
1.配置路由规则,使用路由插件,然后暴露路由
引入vue和vue路由
import Vue from "vue";
import VueRouter from "vue-router";
使用路由插件
Vue.use(VueRouter)
配置路由页面
const routes=[
{
path:"/shop",
name:'shop',
component:shop
}
]
暴露路由
const router=new VueRouter{
routes
}
exporttdefault router2.使用路由 在App.vue中使用路由视图标签即可根据路由规则跳转页面
<div id="root">
<router-view></router-view>
<div>2.路由包含参数配置
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>3.一级路由配置
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>