vue.js 怎么请求数据? 下面本篇文章给大家简单介绍一下 vue.JS 请求数据的几种方式. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
请求数据的方式:
vue-resource 官方提供的 vue 的一个插件
- axios
- fetch-JSONP
一, vue-resource 请求数据
介绍: vue-resource 请求数据方式是官方提供的一个插件
使用步骤:
1, 安装 vue-resource 模块
cnpm install vue-resource --save
加 --save 是为了在 package.JSON 中引用, 表示在生产环境中使用. 因为我们在日常开发中, 如果我们要打包代码给其他人或者上传到 GitHub, 又或者要发布代码时, package.JSON 就是安装所需要的包. 如果只在开发环境中使用, 则只需要 --save-dev, 有一些只在开发环境中用, 有一些要在生产环境中用.
2, 在 main.JS 引入 vue-resource
- import VueResource from 'vue-resource';
- Vue.use(VueResource);
3, 在组件里面直接使用
- this.$http.get(地址).then(function(){
- })
注意: this.$http.get() 等等的各种 http 请求都是继承 promise 的. promise 是异步的请求; 其次,.then 箭头函数里的 this 代表的是上下文. 根据箭头函数 this 的定义, 只在函数定义时就已经赋值可知, this, 指代的是定义函数的对象, 在 vue 中对象就是 methods 当前页面. 所以 this 指导的是 data 里面的数据. 如果想要获取包裹函数外函数的数据, 即闭包的概念. 实现方法就是在外层函数加一个 var that = this; 将外层的 this 先储存到 that 中.
实例:
Info.vue
- <template>
- <div id="info">
- <button @click="getData"> 获取数据 </button>
- <ul>
- <li v-for="(item,index) in list" v-bind:key="index">
- {{item.title}}
- </li>
- </ul>
- </div>
- </template>
- <script>
- export default {
- name: "Info",
- data() {
- return {
- list: []
- }
- },
- methods: {
- getData: function () {
- let API = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
- // 此处推荐使用箭头函数.
- this.$http.get(API).then((res)=>{
- this.list = res.body.result;
- }, (err)=>{
- console.log(err);
- });
- }
- },
- mounted() {
- this.getData();
- }
- }
- </script>
如果 getData() 中不适用箭头函数, 就需要注意 this 问题.
- getData: function () {
- let API = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
- const _this = this;
- this.$http.get(API).then(function (res) {
- _this.list = res.body.result;
- }, function (err) {
- console.log(err);
- });
- }
二, axios 请求数据
介绍: 这是一个第三方的插件 GitHub 地址: https://github.com/axios/axios
axios 与 fetch-JSONP 同为第三方插件
1, 安装
cnpm install axios --save
直接调用. 和 vue-resource 的区别是: aixos 是每在一个页面用一次就要在该页面调用一次. vue-resource 是绑定了全局的了.
2, 哪里用哪里引入 axios
- Axios.get(API).then((response)=>{
- this.list=response.data.result;
- }).catch((error)=>{
- console.log(error);
- })
关于 axios 的跨域请求
在 config->index.JS->proxyTable 配置如下: target 填写自己想要的地址
如下配置, url 为地址后面所带的参数, 配置好后, 现在 NPM run dev 运行就行.
关于多个并发请求:
上面这个是同一地址的跨域, 如果要拿不同地址的跨域, 只需要更改 config->index.JS->proxyTable 的配置, 增加地址块就行.
三, 关于 fetch-JSONP
GitHub 地址: https://github.com/camsong/fetch-jsonp
1, 安装
cnpm install fetch-JSONP --save
2, 哪里用哪里引入 fetch-JSONP
- fetchJsonp('/users.jsonp')
- .then(function(response) {
- return response.JSON()
- }).then(function(JSON) {
- console.log('parsed json', JSON)
- }).catch(function(ex) {
- console.log('parsing failed', ex)
- })
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/vue-js/17055.html