当前位置:首页 > VUE

vue实现联动get

2026-03-30 11:24:58VUE

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);
  });

父子组件联动

父组件传递数据和方法给子组件:

vue实现联动get

<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:

vue实现联动get

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;
        });
    }
  }
};

标签: vueget
分享给朋友:

相关文章

vue 实现豆瓣

vue 实现豆瓣

以下是基于 Vue 实现豆瓣电影类功能的实现方案,涵盖核心模块和技术要点: 数据获取与 API 调用 使用豆瓣开放 API(需注意调用频率限制)或第三方代理接口 推荐 axios 进行异步请求,配合…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

vue实现分发

vue实现分发

Vue 实现分发的方法 在 Vue 中,分发(Distribution)通常指的是将内容从父组件传递到子组件,或者通过插槽(Slots)机制让父组件控制子组件的部分渲染内容。以下是几种常见的实现分发的…

vue键盘实现

vue键盘实现

监听键盘事件 在Vue中监听键盘事件可以通过v-on指令或@缩写实现。常见的键盘事件包括keydown、keyup和keypress。例如监听回车键事件: <template> &l…

vue 实现赋值

vue 实现赋值

Vue 实现赋值的方法 在 Vue 中,赋值操作通常涉及数据绑定和响应式更新。以下是几种常见的赋值方式: 直接赋值给 data 属性 在 Vue 实例的 data 对象中定义的属性可以直接通过 th…