Sử dụng Axios trong Vue CLI phiên bản mới nhất. Cách mà ta ưa dùng để lấy dữ liệu, cách mà Vue 3 xử lý các reactive variables nó sẽ khác so với Vue 2, ta cần cài đặt các biến ( reactive variables ) trong hàm setup()
Cài đặt axios :
npm install axios
Dưới đây là cách mà ta gọi axios trong Vue
import { ref } from 'vue' import axios from 'axios' import { RouterLink } from 'vue-router' export default { name: 'ProductView', setup() { const products = ref([]) const count = ref(0) const getAllProducts = () => { axios.get('https://dummyjson.com/products').then((res) => { products.value = res.data.products console.log(products.value) count.value = products.value.length }) } // call function getAllProducts() return { products, count } } }
Nó sẽ trả về console.log như sau :
Ok, còn các reactive variables (products, count), muốn sử dụng nó, ta cần phải return {products, count)
<template> <div class="w-full max-w-6xl m-auto"> <h1 class="w-full font-bold uppercase text-xl text-gray-500 py-5 block"> Products List of number {{ count }} </h1> <table class="w-full text-sm text-left text-gray-500"> <thead class="text-xs text-gray-700 uppercase bg-gray-300"> <tr> <th scope="col" class="px-6 py-3">ID</th> <th scope="col" class="px-6 py-3">Title</th> <th scope="col" class="px-6 py-3">Category</th> <th scope="col" class="px-6 py-3">Price</th> <th scope="col" class="px-6 py-3">Rating</th> <th scope="col" class="px-6 py-3">Stock</th> <th scope="col" class="px-6 py-3">Tags</th> <th scope="col" class="px-6 py-3">Modify</th> </tr> </thead> <tbody> <tr class="bg-white border-b" v-for="product in products" :key="product.id"> <th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap"> {{ product.id }} </th> <td class="px-6 py-4">{{ product.title }}</td> <td class="px-6 py-4">{{ product.category }}</td> <td class="px-6 py-4">{{ product.price }}</td> <td class="px-6 py-4">{{ product.rating }}</td> <td class="px-6 py-4">{{ product.stock }}</td> <td class="px-6 py-4"> <span v-for="tag in product.tags" class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2" > {{ tag }} </span> </td> <td> <span class="inline-block bg-yellow-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2" ><RouterLink :to="`/edit/${product.id}`">Edit</RouterLink></span > <span class="inline-block bg-red-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2" ><RouterLink :to="`/delete/${product.id}`">Delete</RouterLink></span > </td> </tr> </tbody> </table> </div> </template>
DEMO