第十节:Vue-ReSource-axios

第十节:Vue-ReSource-axios

vue-resource 是官方的异步请求数据的一个插件,内部对Ajax进行了封装axios,是请求后台数据的组件。

1、安装 vue-resource

  • 打开终端 切换到项目根目录。
  • 输入安装命令:npm install --save vue-resource 等待安装完成

2、注册插件

  • 插件安装完成之后,还需要通过 Vue.use() 方法进行引用。一般情况我们 main.js 根组件中进行注册引用。

  • Vue 项目中使用

// 导入 vue-resource 模块 
import vueResource from 'vue-resource';
// 注册 vue-resource 模块
Vue.use(vueResource);
  • 在页面中应用
通过script标签,引入vue-resource的脚本文件;引用的先后顺序是 - 先引用Vue的脚本文件,再引用vue-resource的脚本文件。

GET请求:

methods: {
    getInfo: function () {
        // get 方式获取数据 
        this.$http.get('http://yapi.shangyuninfo.com/mock/36/web02/category').then(res => {
            console.log(res.body);
        })
    }
}

POST请求:

methods: {
    postInfo: function () {
        var url = ' http://yapi.shangyuninfo.com/mock/36/web02/list/goods/category';
        // post 方法接收三个参数:
        // 参数1: 要请求的URL地址
        // 参数2: 要发送的数据对象
        // 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
        this.$http.post(url, {
            categoryId: 'zs'
        }, {
            emulateJSON: true
        }).then(res => {
            console.log(res.body);
        });
    }
}

jsonnp请求:

request () {
    var api = '/api/v1/assessment/list?profile_id=40651&token=02%E2%80%A6a0797ea3285ad583d16&type=1&page_no=1&page_size=50';
    // 发起get请求
    this.$http.jsonp(api)
        .then(req => {// 请求成功
            console.log(req);
        }, err => {// 请求失败
            console.log(err);
        });
}

3、axios的使用

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
 
<body>
    <div id='app'>
        <div v-for="item in list" :key=item.id>
            {{item.category}}
        </div>
    </div>
 
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                list: []
            },
            methods: {},
            created() {
                // GET
                axios.get("http://yapi.shangyuninfo.com/mock/36/web02/category").then(res => {
                    this.list = res.data.data
                })
                // post 只有两个参数 1 地址 2 请求体
                // 通过内置对象,创建对应格式的请求体
                //URLSearchParams对应的请求格式application/x-www-form-urlencoded
                let url = new URLSearchParams()
                url.append("type", "free")
                url.append("pageNum", 1)
                url.append("pageSize", 5)
                let form = new FormData()
                // append两个参数 1 属性名 2 属性值 中间是逗号
                form.append("type", "free")
                form.append("pageNum", 1)
                form.append("pageSize", 5)
                axios.post("http://wkt.myhope365.com/weChat/applet/course/list/type",form).then(res=>{
                    console.log(res);
                })
                let json = {"enable":1}
                axios.post("http://wkt.myhope365.com/weChat/applet/subject/list",json).then(res=>{
                    console.log(res);
                })
            }
        })
    </script>
</body>
 
</html>

4、Vue中使用

vue中应用vue-resource

// main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';

// 导入 vue-resource 模块
import VueResource from 'vue-resource';
// 注册 vue-resource 模块
Vue.use(VueResource);


/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

// template.vue
<!-- 模板结构 -->
<template>
  <div>
    <button @click="reqList">request</button>
  </div>
</template>

<!-- 脚本 -->
<script>
export default {
    methods:{
        reqList(){
            var api = '/api/v1/assessment/list?profile_id=40651&token=02%E2%80%A6a0797ea3285ad583d16&type=1&page_no=1&page_size=50';
            // 发起get请求
            this.$http.get(api)
            .then(req=>{// 请求成功
                console.log(req);
            },err=>{// 请求失败
                console.log(err);
            });

        }
    }
}
</script>

<!-- 样式 -->
<style>
</style>

5、单文件组件

​ 单文件组件需要在vue-cli开发环境下才能使用。其本质依旧是一个局部组件,不过顾名思义,每个组件都是一个单独的文件,文件后缀名为.vue。当需要使用组件的时候直接导入组件文件。单文件组件的结构主要分为三个部分:

  • 模板结构

  • 脚本

  • 样式

单文件组件的命名一般以大写字母开头,后缀名为:.vue ,单文件组件中包含 htmlcssjs

<!-- TestComponent.vue -->

<!-- 模板结构 -->
<template>
  <div>
    <p>模板结构部分</p>
    <p>{{ mess }}</p>
  </div>
</template>

<!-- 脚本 -->
<script>
// 组件参数对象 'export default' 为导出对象,固定的写法
export default {
    data(){
        return {
            mess:'hello~'
        }
    }
}
</script>

<!-- 样式 -->
<style>
    p{
        color:red;
    }
</style>

6、单文件组件的导入

​ 单文件组件的导入,比本地导入多一个步骤,也就是需要先引用文件。其他与一般组件的使用没有太多区别。基于vue-cli的环境下会有一个根组件 App.vue 这个组件一般我们不会直接在里面去写内容。而只是在其中做组件导入等等的这些工作

<!-- App.vue -->

<template>
  <div id="app">
    
    <!-- 使用组件 -->
    <v-test></v-test>

  </div>
</template>

<script>

// 导入组件文件
import vTest from '@/components/TestComponent.vue';

export default {
  components:{
    // 注册组件
    'v-test':vTest
  }
}
</script>

<style>

</style>

7、异步组件

默认情况下,所有的组件文件是同步加载的。这在应用体积比较庞大的时候加载效率是比较低的。所以很多时候我们可以在需要使用某个组件的时候异步的去加载组件。在 vue-cli 通过webpack的打包功能能够轻松实现异步的加载

  • 普通导入的异步组件

    import vComponentA from '@/components/Login.vue';// 同步加载
    const vComponentA = ()=>import('@/components/Home.vue');// 异步加载 webpack 2.X+
    
  • 路由组件导入

    import vHome from '../components/Home.vue';
    
    const routes = [
    	{
    		path:'/',
    		component:vHome
    	},
    	{
    		path:'/user',
    		component:()=>import('../components/Login.vue'),// 需要导入一个函数并且返回
    		children:[
    			{
    				path:'content',
    				component:()=>import('../components/Home.vue')// 子路由同理
    			}
    		]
    	}
    ];
    
  • 加载状态处理

可以通过返回一个对象,来对异步的加载状态的处理,比如加载失败的时候使用的模板,加载等待时间等等

const AsyncComponent = () => ({
  // 需要加载的组件 (应该是一个 `Promise` 对象)
  component: import('./MyComponent.vue'),
  // 异步组件加载时使用的组件
  loading: LoadingComponent,
  // 加载失败时使用的组件
  error: ErrorComponent,
  // 展示加载时组件的延时时间。默认值是 200 (毫秒)
  delay: 200,
  // 如果提供了超时时间且组件加载也超时了,
  // 则使用加载失败时使用的组件。默认值是:`Infinity`
  timeout: 3000
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小戈&328

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值