webpack+vuex+axios 跨域請求數(shù)據(jù)的示例代碼
更新時間:2018年03月06日 11:25:21 作者:清兒
本篇文章主要介紹了webpack+vuex+axios 跨域請求數(shù)據(jù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了webpack+vuex+axios 跨域請求數(shù)據(jù)的示例代碼,分享給大家,具體如下:
使用vue-li 構(gòu)建 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 中想跨域請求
設(shè)置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) }) }
組件內(nèi)使用:
<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>
在組件內(nèi)想跨域
在main.js設(shè)置:
import axios from 'axios' // 將 axios 改寫為 Vue 的原型屬性,使在其它的組件中可以使用 axios Vue.prototype.$axios = axios
在組件內(nèi)設(shè)置:
<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>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Vue3+Vant組件實現(xiàn)App搜索歷史記錄功能(示例代碼)
最近接了個項目需要開發(fā)一個app項目,由于是第一次接觸這種app開發(fā),經(jīng)過一番思考,決定使用Vue3+Vant前端組件的模式進行開發(fā),下面把問題分析及實現(xiàn)代碼分享給大家,需要的朋友參考下吧2021-06-06Vue3結(jié)合TypeScript項目開發(fā)實踐總結(jié)
本文主要介紹了Vue3結(jié)合TypeScript項目開發(fā)實踐總結(jié),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09vue 接口請求地址前綴本地開發(fā)和線上開發(fā)設(shè)置方式
這篇文章主要介紹了vue 接口請求地址前綴本地開發(fā)和線上開發(fā)設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08