vue实现ajax数据渲染
Vue 实现 AJAX 数据渲染
Vue 结合 AJAX 实现数据渲染的核心是通过异步请求获取数据,再通过响应式机制更新 DOM。以下是具体实现方法:
使用 Axios 发送 AJAX 请求
安装 Axios 依赖:
npm install axios
在 Vue 组件中引入 Axios:
import axios from 'axios';
发送 GET 请求并渲染数据:
export default {
data() {
return {
items: []
};
},
created() {
axios.get('https://api.example.com/items')
.then(response => {
this.items = response.data;
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
};
模板中渲染数据:
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
使用 Vue Resource(Vue 1.x/2.x 旧项目)
安装 Vue Resource:
npm install vue-resource
在 main.js 中引入:
import VueResource from 'vue-resource';
Vue.use(VueResource);
组件中使用:
this.$http.get('/api/items').then(response => {
this.items = response.body;
}, error => {
console.error(error);
});
使用 Fetch API(原生方案)
无需安装额外库:
fetch('https://api.example.com/items')
.then(response => response.json())
.then(data => {
this.items = data;
})
.catch(error => {
console.error('Error:', error);
});
异步/await 写法
ES7 语法更简洁:
async created() {
try {
const response = await axios.get('/api/items');
this.items = response.data;
} catch (error) {
console.error(error);
}
}
加载状态处理
添加 loading 状态提升用户体验:
data() {
return {
items: [],
isLoading: false,
error: null
};
},
methods: {
async fetchData() {
this.isLoading = true;
try {
const response = await axios.get('/api/items');
this.items = response.data;
} catch (err) {
this.error = err.message;
} finally {
this.isLoading = false;
}
}
}
模板中添加状态显示:
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">{{ error }}</div>
<ul v-else>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
注意事项
- 跨域问题需配置 CORS 或代理
- 大型项目建议将 API 请求封装成 service 模块
- 考虑使用 Vuex 管理全局状态时,应将请求放在 actions 中
- 列表渲染务必添加
:key提升性能







