本篇文章主要介紹了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>
上面是我整理給大家的,希望今後會對大家有幫助。
相關文章:
以上是利用webpack+vuex+axios這些技術實現跨域請求資料(詳細教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!