Vue中使用axios与服务端交互

Vue中Javascript与服务端的异步数据交互,都是推荐使用axios库,而不是之前使用jQuery中的ajax方式。的确axios在使用起来也是非常方便,而在Vue中使用jQuery还需要增加一系列配置,总体jQuery与Vue不是非常契合。这里总结一下Vue中使用axios的基本用法。

以下没有贴所有的代码,可能有信息缺失引起歧义,可以发送邮件到hugh@inner-peace.cn 咨询和探讨。

假设project中有一个x.vue的component,其中script标签如下,目的是展示服务端传回来的一个数组,并展示在table标签中。

<template>
	<table>
		<thead>
			<tr>
				<th>id</th>
				<th>name</th>
				<th>desc</th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="item in items" :key="stock.name">
				<td>{{item.id}}</td>
				<td>{{item.name}}</td>
				<td>{{item.desc}}</td>
			</tr>
		</tbody>
	</table>
</template>

以上的代码使用了v-for来做循环,但是在Vue2.0中,需要增加:key指定key,否则会有warning。

接下来是x.vue的script标签内容

<script>
    import axios from 'axios';
	export default {
      name: 'X',
      data() {
          return {
              items: []
          }
      },
      mounted () {
          axios.get('/api?p1=123&p2=abc')
          	.then(response => {
              if (response.data.hasOwnProperty('items')) {
                  this.items = response.data.items;
              }
          });
      }
    };
</script>

其中服务端返回的数据如下。

{"status":0, "items":[{"id":1, "name":"a", "desc":"this is a"}, {"id":2, "name":"b", "desc":"this is b"}]}

这样就可以成功交互数据了。但有几个细节需要关注,容易出错。

  • axois的response会自动进行json解析。因为axios的response有一个default的transformResponse函数处理,使用JSON.Parse进行转换,因此如果返回的是json字符串,那么response对象已经是json转换后的Javescript Object;

  • 服务端拼接的json字符串中的key必须有双引号。否则解析会出现问题,即response.data.items会出现获取为空;

  • 开发环境服务端的配置。axios.get后面如果直接使用路径,在dev环境下需要配置config中的index.js,如下

    // index.js文件
    ...
      
    module.exports = {
        dev: {
            proxyTable: {
                '/api': {
                    target: 'http://123.456.7.89:8000',
                    changeOrigin: false
                }
            },
            ...
        }
    ...
    }