Vue.js实现点击列表选项触发API请求更新产品数据
解决Vue组件点击选项未触发API请求的问题
你的核心问题是API请求仅在组件初始化时执行了一次,created生命周期钩子只会在组件创建阶段运行一次,后续修改product值不会自动触发新的请求。下面是两种直接可行的修复方案:
方案一:点击时直接调用请求方法
把API请求逻辑抽成独立方法,在点击事件中修改product后立即调用该方法:
<template> <div> <h1 class="text-center text-4xl font-bold">Our Product</h1> <ul class="flex items-center justify-center gap-5"> <li class="cursor-pointer text-xl" @click="handleClick(1)">Clothes</li> <li class="cursor-pointer text-xl" @click="handleClick(5)">Shoes</li> <li class="cursor-pointer text-xl" @click="handleClick(2)">Watches</li> <li class="cursor-pointer text-xl" @click="handleClick(4)">Furniture</li> </ul> <div class="grid grid-cols-3 gap-5"> <div v-for="store in stores" :key="store.id"> <!-- 改用store.id作为key,避免分类重复导致key冲突 --> <div class="max-w-xl h-auto"> <img :src="store.images[0]" alt="Product image" /> </div> </div> </div> </div> </template> <script> import axios from "axios"; export default { components: { // 未用到的组件可删除 // Clothes, // Shoes, }, data() { return { stores: [], errors: [], product: 1, // Options API中直接定义变量即可,Vue会自动处理响应式,无需手动用ref }; }, methods: { async handleClick(params) { this.product = params; await this.fetchProducts(); // 修改product后立即发起新请求 }, async fetchProducts() { try { const res = await axios.get( `https://api.escuelajs.co/api/v1/categories/${this.product}/products` ); this.stores = res.data; console.log(this.stores); } catch (e) { this.errors.push(e); console.error(e); // 直接打印错误信息,便于调试 } }, }, async created() { await this.fetchProducts(); // 组件初始化时加载默认数据 }, }; </script>
方案二:用watch监听product变化
通过watch监听product的变化,一旦值更新就自动发起请求:
<template> <!-- 模板部分与方案一一致 --> </template> <script> import axios from "axios"; export default { components: { // 按需保留组件 }, data() { return { stores: [], errors: [], product: 1, }; }, methods: { handleClick(params) { this.product = params; }, async fetchProducts() { try { const res = await axios.get( `https://api.escuelajs.co/api/v1/categories/${this.product}/products` ); this.stores = res.data; console.log(this.stores); } catch (e) { this.errors.push(e); console.error(e); } }, }, async created() { await this.fetchProducts(); }, watch: { // 监听product值变化,自动触发请求 async product() { await this.fetchProducts(); }, }, }; </script>
额外优化提示
- 响应式变量使用:你在
data中用了ref(1),但Options API里data返回的对象会被Vue自动转为响应式,直接写product: 1即可,无需手动调用ref。 - key值规范:原代码用
store.category.id作为v-for的key,若多个产品属于同一分类会导致key重复,建议改用唯一的store.id。 - 错误处理:原代码中
console.log(this.errors.push(e))会打印数组长度,换成console.error(e)更直观展示错误详情。
内容的提问来源于stack exchange,提问作者Mayowa
相关产品推荐
相关产品推荐

