Vue CLI中News API动态可点击URL实现问题求助
Hey there! Let's get those article links working properly—it's a quick fix, I promise 😊
The Problem
Right now, you've hardcoded adress as the string "item.url" in your component's data, and you're binding that static value to all your links. That's why the links aren't pointing to the actual article URLs—they're just trying to go to a literal page named "item.url"!
The Simple Solution
You don't need that adress variable at all. Instead, you can directly bind each item's url property to your anchor tag's href attribute. Here's how to update your code:
Updated Template
<template> <div class="api"> <h1>Latest gossip</h1> <br /> <div v-for="item of items" v-bind:key="item.id"> <h3>{{ item.title }}</h3> <p>{{ item.description }}</p> <!-- Directly bind to item.url, and use friendlier link text --> <a v-bind:href="item.url" target="_blank">Read full article</a> </div> </div> </template>
(Added target="_blank" so the article opens in a new tab—optional but user-friendly!)
Updated Script
You can remove the unused adress property from your data:
<script> import axios from "axios"; export default { name: "Api", props: ["articles"], data() { return { items: [] // Removed the unused 'adress' variable }; }, mounted() { this.getInfo(); }, methods: { getInfo() { axios({ method: "GET", url: "https://cors-anywhere.herokuapp.com/https://newsapi.org/v2/top-headlines?country=se&category=entertainment&apiKey=XXX", dataType: "json", headers: { "X-Requested-With": "XMLHttpRequest", "Access-Control-Allow-Origin": "*" } }).then(res => { console.log(res.data); this.items = res.data.articles; }); } } }; </script>
How This Works
Now, every time Vue loops through your items array, it'll grab the unique url from each article object and bind it to the corresponding anchor tag. Clicking the link will take you straight to the full article!
内容的提问来源于stack exchange,提问作者Anna Bergman

