webpack+vuex+axios 跨域請求資料的範例程式碼,webpackvuex

來源:互聯網
上載者:User

webpack+vuex+axios 跨域請求資料的範例程式碼,webpackvuex

本文介紹了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 的原型屬性,使在其它的組件中可以使用 axiosVue.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>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.