添加vue-router
js
npm install vue-router
配置路由
新建一个router文件夹,在router文件夹下新建index.ts文件,内容如下
js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{path:'/',component:()=>import('../views/Home.vue')},
{path:'/manager',component:()=>import('../views/GoodManager.vue')},
{path:'/adder',component:()=>import('../views/GoodAdder.vue')},
{path:'/about',component:()=>import('../views/About.vue')},
]
});
export default router
注册路由
在main.ts中注册路由,内容如下:
js
import router from './router'
createApp(App).use(router).mount('#app')
配置路由链接
在App.vue中配置路由链接,内容如下:
xml
<template>
<router-link to="/">首页</router-link> |
<router-link to="/manager">商品管理</router-link> |
<router-link to="/adder">商品添加</router-link> |
<router-link to="/about">关于</router-link> |
<hr>
<router-view></router-view>
</template>
首页(商品分类): ./views/Home.vue
> <h1>管理首页</h1>
<!-- 进行商品分类信息的渲染 -->
<table>
<thead>
<tr><th>ID</th><th>名称</th><th>图片</th><th>商品种类</th><th>价格合计</th></tr>
</thead>
<tbody>
<tr v-for="cat in categories" :v-key="cat.id">
<td>{{ cat.id }}</td>
<td>{{ cat.name }}</td>
<td>
<img :src="BASE_URL+'images/'+cat.image" width="100px">
</td>
<td>0</td><td>¥0.0</td>
</tr>
</tbody>
</table>
</template>
<script lang="ts" setup>
import { onMounted,ref } from 'vue'
//后端服务的访问地址
const BASE_URL="http://localhost:3000/"
// const BASE_URL="http://johnyu.cn:3000/categories"
//定义一个响应式数据,用于存储商品分类信息
const categories=ref([])
//在页面加载完成后从服务器获取商品分类信息
//此处使用了JS异步函数
onMounted(async ()=>{
const resp=await fetch(BASE_URL+"categories");
const data=await resp.json();
categories.value=data;
})
</script>