webpack+vuex+axios 跨域请求数据的示例代码
更新时间:2018年03月06日 11:25:21 作者:清儿
本篇文章主要介绍了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
laravel+vue组合的项目中引入ueditor方式(打包成组件形式)
今天小编就为大家分享一篇laravel+vue组合的项目中引入ueditor方式(打包成组件形式),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-11-11
Vue3使用sessionStorage保存会话数据的实现方式
在前端开发中,我们常常需要在用户会话期间保存一些数据,这些数据在页面刷新或导航时依然需要存在,sessionStorage 是一种非常方便的方式来实现这一点,在这篇文章中,我们将探讨如何在Vue3应用中使用sessionStorage来保存会话数据,需要的朋友可以参考下2025-01-01
Vue插槽_特殊特性slot,slot-scope与指令v-slot说明
这篇文章主要介绍了Vue插槽_特殊特性slot,slot-scope与指令v-slot说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09


最新评论