您好,欢迎访问一九零五行业门户网

利用webpack+vuex+axios这些技术实现跨域请求数据(详细教程)

本篇文章主要介绍了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> <p class="movie-page"> <ul class="clearfix"> <movies-item v-for="(item,index) in movie_list" :key="index" :movie="item"></movies-item> </ul> </p> </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> <p class="movie-page"> <ul class="clearfix"> <movies-item v-for="(item,index) in movie_list" :key="index" :movie="item"></movies-item> </ul> </p> </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>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
vue.js实现图片的随意拖动方法
解决vue 通过下表修改数组,页面不渲染的问题
vue2.0 axios跨域并渲染的问题解决方法
以上就是利用webpack+vuex+axios这些技术实现跨域请求数据(详细教程)的详细内容。
其它类似信息

推荐信息