vue实现后端数据预览
使用 Axios 获取后端数据
在 Vue 项目中安装 Axios:
npm install axios
在组件中引入 Axios 并发送请求:
import axios from 'axios';
export default {
data() {
return {
items: []
};
},
created() {
axios.get('https://api.example.com/data')
.then(response => {
this.items = response.data;
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
};
展示数据列表
在模板中使用 v-for 渲染数据:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} - {{ item.value }}
</li>
</ul>
</div>
</template>
添加加载状态和错误处理
在数据加载时显示加载状态,捕获错误并提示用户:
data() {
return {
items: [],
loading: false,
error: null
};
},
methods: {
fetchData() {
this.loading = true;
axios.get('https://api.example.com/data')
.then(response => {
this.items = response.data;
this.loading = false;
})
.catch(error => {
this.error = 'Failed to load data';
this.loading = false;
});
}
},
created() {
this.fetchData();
}
在模板中显示加载和错误状态:
<div v-if="loading">Loading...</div>
<div v-else-if="error" class="error">{{ error }}</div>
<ul v-else>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
分页和搜索功能
实现分页和搜索功能,动态更新数据:
data() {
return {
items: [],
currentPage: 1,
totalPages: 0,
searchQuery: ''
};
},
methods: {
fetchData() {
axios.get('https://api.example.com/data', {
params: {
page: this.currentPage,
search: this.searchQuery
}
})
.then(response => {
this.items = response.data.items;
this.totalPages = response.data.totalPages;
});
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
}
},
created() {
this.fetchData();
}
在模板中添加分页和搜索控件:
<input v-model="searchQuery" @input="fetchData" placeholder="Search...">
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
使用 Vuex 管理状态
在大型项目中,使用 Vuex 集中管理数据状态:
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
items: [],
loading: false
},
mutations: {
SET_ITEMS(state, items) {
state.items = items;
},
SET_LOADING(state, loading) {
state.loading = loading;
}
},
actions: {
async fetchItems({ commit }) {
commit('SET_LOADING', true);
try {
const response = await axios.get('https://api.example.com/data');
commit('SET_ITEMS', response.data);
} catch (error) {
console.error(error);
} finally {
commit('SET_LOADING', false);
}
}
}
});
在组件中调用 Vuex action:
export default {
computed: {
items() {
return this.$store.state.items;
},
loading() {
return this.$store.state.loading;
}
},
created() {
this.$store.dispatch('fetchItems');
}
};






