webpack+vuex+axios 跨域请求数据的示例代码

人来到这世界后,命运注定了他必须要拼搏,奋斗,坚持,勇敢地走下去,走出属于自己的道路,没有人能不劳而获。

本文介绍了webpack+vuex+axios 跨域请求数据的示例代码,分享给大家,具体如下:

使用vue-li 构建 webpack项目,修改bulid/config/index.js文件

dev: {
  env: require('./dev.env'),
  port: process.env.PORT || 8080,
  autoOpenBrowser: true,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
   '/v2': {
     target: 'http://api.douban.com',
     changeOrigin: true,
     pathRewrite: {
      '^/v2': '/v2'
    } 
   }
  },
 }

在action.js 中想跨域请求

设置action.js:

import axios from 'axios'

export const GET_IN_THEATERS = ({
 dispatch,
 state,
 commit
}) => {
 axios({
  url: '/v2/movie/in_theaters'
 }).then(res => {
  commit('in_theaters', res.data)
 })
}

组件内使用:

<template>
  <div class="movie-page">
    <ul class="clearfix">
      <movies-item v-for="(item,index) in movie_list" :key="index" :movie="item"></movies-item>
    </ul>
  </div>
</template>
<script>
import {mapState, mapActions, mapGetters} from 'vuex';
import MoviesItem from "./movie-item";
export default {
  data () {
    return {
      
    }
  },
  components: {
    MoviesItem
  },
  computed: {
    ...mapState({
      movie_list: state => {
        return state.in_theaters.subjects
      }
    })
  },
  methods: {
    
  },
  created () {
    this.$store.dispatch('GET_IN_THEATERS')
  },
  mounted () {
  }
}
</script>
<style lang="scss">
@import "./../../assets/reset.scss";
@import "./../../assets/main.scss";
.movie-page{
  padding: 0 rem(40);
}
</style>

在组件内想跨域

在main.js设置:

import axios from 'axios'
// 将 axios 改写为 Vue 的原型属性,使在其它的组件中可以使用 axios
Vue.prototype.$axios = axios

在组件内设置:

<template>
  <div class="movie-page">
    <ul class="clearfix">
      <movies-item v-for="(item,index) in movie_list" :key="index" :movie="item"></movies-item>
      
    </ul>
  </div>
</template>
<script>
import MoviesItem from "./movie-item";
export default {
  data () {
    return {
      movie_list: []
    }
  },
  components: {
    MoviesItem
  },
  computed: {
    
  },
  methods: {
  },
  created () {
    
  },
  mounted () {
    this.$axios.get('/v2/movie/in_theaters').then(res => {
      this.movie_list = res.data.subjects
    }, res => {
      console.infor('error')
    })
  }
}
</script>
<style lang="scss">
@import "./../../assets/reset.scss";
@import "./../../assets/main.scss";
.movie-page{
  padding: 0 rem(40);
}
</style>

本文webpack+vuex+axios 跨域请求数据的示例代码到此结束。吸取教训是健康的做法,这是个人成长过程中的必要环节。悔恨则是一种不健康的心理。这是白白浪费自我目前的精力。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
vue+webpack 更换主题N种方案优劣分析

如何使用webpack搭建vue环境的好代码教程详解

webpack+vue.javascript构建前端工程化的详细好代码教程

基于vuejavascript+webpack的日期选择插件

浅析vue-cli3配置webpack-bundle-analyzer插件【推荐】