vue使用axios并存数据到state

npm安装

npm install axios --save

main.js导入

// 引入axios,并加到原型链中
import Axios from 'axios'
import QS from 'qs'
Vue.prototype.$axios = Axios
Vue.prototype.qs = QS

各子模块中使用,通过原型链 this.$axios ......

get实例

<div id="app">
  <h1>网站列表</h1>
  <div
    v-for="site in info"
  >
    {{ site.name }}
  </div>
</div>
<script type = "text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios.get('https://www.xxxx.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch(function (error) { // 请求失败处理
        console.log(error);
      });
  }
})
</script>

post实例

<script>
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios.post('https://www.xxxxx.com/try/ajax/demo_axios_post.php', {
      firstName: 'Fred',        // 参数 firstName
      lastName: 'Flintstone'    // 参数 lastName
  })
      .then(response => (this.info = response))
      .catch(function (error) { // 请求失败处理
        console.log(error);
      });
  }
})
</script>

执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

axios API

axios(config)
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
//  GET 请求远程图片
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');
发布了65 篇原创文章 · 获赞 11 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/u011280778/article/details/100190642
今日推荐