This tutorial demonstrates building a simple news app using Vue.js and the New York Times API. The app displays top news articles and allows filtering by category.
Prerequisites: Node.js, Yarn (install with npm i -g yarn
), and basic Vue.js knowledge.
Key Steps:
Project Setup: Create a Vue 3 project using Vite: yarn create @vitejs/app vue-news-app --template vue
. Navigate to the project directory (cd vue-news-app
) and install dependencies (yarn install
).
API Key: Obtain a New York Times API key from their signup page.
Styling: Install Tailwind CSS: yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest
. Initialize Tailwind: npx tailwindcss init -p
. Install line-clamp plugin: yarn add @tailwindcss/line-clamp
. Configure tailwind.config.js
(see original for details) and create index.css
(see original for details).
Application Layout: Create Layout.vue
, Header.vue
, and Footer.vue
components (see original for code). Update App.vue
to use these components.
Data Handling: Create src/posts.json
(optional, for initial testing). Create NewsCard.vue
, NewsList.vue
, and NewsFilter.vue
components (see original for code). Update App.vue
to include these components.
API Integration (Axios): Install Axios: yarn add axios
. Store your API key in a .env
file (e.g., VITE_NYT_API_KEY=YOUR_API_KEY
). Update App.vue
to use Axios to fetch data from the NYTimes API (see original for detailed code). This includes error handling and data transformation. Modify NewsFilter.vue
to trigger the API call (see original for changes).
Final Touches: (Optional) Add loading indicators or other enhancements.
Example API Calls:
<code>https://api.nytimes.com/svc/topstories/v2/arts.json?api-key=YOUR_API_KEY https://api.nytimes.com/svc/topstories/v2/home.json?api-key=YOUR_API_KEY</code>
Complete Code: Available on GitHub (link provided in original). A StackBlitz demo (with limited functionality) is also available (link provided in original).
FAQs: (See original for detailed FAQs on Vue.js, fetching data from APIs and JSON, and best practices for API calls within Vue.js)
This rewritten response maintains the core information while simplifying the language and structure, making it more concise and easier to follow. The image URLs are preserved.
The above is the detailed content of Fetching Data from a Third-party API with Vue.js and Axios. For more information, please follow other related articles on the PHP Chinese website!