欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue中使用axios发送ajax请求,获取数据

程序员文章站 2022-07-10 21:34:41
1、先准备好一个api接口 http://www.imooc.com/api/home/slider 2、安装插件 cnpm install --save axios 3、api/slider.js import axios from 'axios'; //获取幻灯片数据 ajax export c ......

1、先准备好一个api接口 

2、安装插件 cnpm install --save axios

vue中使用axios发送ajax请求,获取数据

 

 

3、api/slider.js

import axios from 'axios';

//获取幻灯片数据 ajax
export const getsliders=()=>{
    return axios.get('http://www.imooc.com/api/home/slider').then(res=>{
        
        if(res.data.code===0){
            console.log(res.data.slider);
            return res.data.slider;//返回是数据
        }

        throw new error('没有成功获取到数据');
    }).catch(err=>{
        console.log(err);
        //错误处理
        return [{       
            linkurl:'www.baidu.com',
            picurl:require('assets/img/404.png')
        }]
    });
}

 

4、在 components/slider/index.vue中引入该方法

<template>
  <swiper ref="myswiper" :options="swiperoptions">
    <swiper-slide v-for="(slider,index) in sliders" :key="index">
        <a :href="slider.linkurl">
            <img :src="slider.picurl">
        </a>
    </swiper-slide>
    <div class="swiper-pagination" slot="pagination"></div>
    <div class="swiper-button-prev" slot="button-prev"></div>
    <div class="swiper-button-next" slot="button-next"></div>
  </swiper>
</template>

<script>
import { swiper, swiperslide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
import { getsliders } from 'api/slider';
 
export default {
    name:"slider",
    title: 'autoplay',
    components:{
        swiper,
        swiperslide
    },
    data() {
      return {
        sliders:[],
        swiperoptions: {
          spacebetween: 30,
          centeredslides: true,
          autoplay: {
            delay: 2500,
            disableoninteraction: false
          },
          loop: true,
          pagination: {
            el: '.swiper-pagination',
            clickable: true
          },
          navigation: {
            nextel: '.swiper-button-next',
            prevel: '.swiper-button-prev'
          }
        }
      }
    },
    created(){
        //一般在created里获取远程数据
        this.getsliders();      
    },
    computed: {
      swiper() {
        return this.$refs.myswiper.$swiper;
      }
    },
    mounted() {
      //console.log('current swiper instance object', this.swiper);
      this.swiper.slideto(3, 1000, false);
    },
    methods:{
        getsliders(){
            return getsliders().then(data=>{
                //console.log(data);
                this.sliders=data;
            });
        }
    }
  }
</script>

<style lang="scss" scoped>
    .swiper-container{
        width:100%;
        height:180px;
    }
    .swiper-slide a{
        display:block;
        width:100%;
        height:100%;

        & img{
            width:100%;
            height:100%;
        }
    }
</style>

 

效果图

vue中使用axios发送ajax请求,获取数据