vue实现联动get
Vue 实现联动 GET 请求
使用 Axios 发送 GET 请求
安装 Axios 依赖:
npm install axios
在 Vue 组件中引入 Axios:
import axios from 'axios';
发送 GET 请求:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
父子组件联动
父组件传递数据和方法给子组件:

<template>
<ChildComponent :data="parentData" @update="fetchData" />
</template>
<script>
export default {
data() {
return {
parentData: []
};
},
methods: {
fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
this.parentData = response.data;
});
}
}
};
</script>
子组件触发父组件方法:
<template>
<button @click="$emit('update')">更新数据</button>
</template>
<script>
export default {
props: ['data']
};
</script>
使用 Vuex 管理状态
安装 Vuex:

npm install vuex
创建 store:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
apiData: []
},
mutations: {
SET_API_DATA(state, payload) {
state.apiData = payload;
}
},
actions: {
async fetchData({ commit }) {
const response = await axios.get('https://api.example.com/data');
commit('SET_API_DATA', response.data);
}
}
});
组件中调用:
export default {
computed: {
apiData() {
return this.$store.state.apiData;
}
},
created() {
this.$store.dispatch('fetchData');
}
};
使用 watch 监听变化
监听数据变化并自动发送请求:
export default {
data() {
return {
query: '',
results: []
};
},
watch: {
query(newVal) {
axios.get(`https://api.example.com/search?q=${newVal}`)
.then(response => {
this.results = response.data;
});
}
}
};






