Vue.js的axios && fetch &&计算属性 && 侦听属性 @ stage3---week2--day1

axios

理解静态请求:

因为我们现在流行的事前后端分离, 所以当后端还没有给我们接口的时候, 我们也需要正常进行开发, 所以我们需要进行数据模拟

  • 数据模拟:
    • 1. 爬取线上的, 拷贝 copy response
      
    • 2. 使用mock.js来生成
      
    • 3. easy mock 这是线上静态网站, 用于接口的暴露
      

axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • axios是XMLHTTPRequest 对象

  • axios底层是Node.js的http模块

  • axios也是Promise

  • axios对数据进行了封装

  • axios可以防止 XSRF 脚本攻击

  • Make XMLHttpRequests from the browser

  • Make http requests from node.js

  • Supports the Promise API

  • Intercept request and response

  • Transform request and response data

  • Cancel requests

  • Automatic transforms for JSON data

  • Client side support for protecting against XSRF

axios的get 请求

axios.get('url', {
        params: {
            name: 'zhanghaioyu',
            gender: 'man',
            age: 24
        }
    })
    .then((ret) => {
        console.log(ret.data);
    })
    .catch(err => console.log(err))
    .finally(function() {
        console.log('finally')
    });

axios({
        url: 'url',
        method: 'get',
        params: {
            name: 'lishanyu',
            gender: 'woman',
            age: 23
        }
    })
    .then((ret) => {
        console.log(ret.data);
    })
    .catch(err => console.log(err))
    .finally(function() {
        console.log('finally')
    });

axios 的post请求

注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑



axios.post(`../`, {
        name: 'zhanghaolin',
        gender: 'man',
        age: '11'
    })
    .then((ret) => {
        console.log(ret.data);
    })
    .catch(err => console.log(err))
    .finally(function() {

    });

解决方法
// 1. 先设置请求头
// 2. 实例化 URLSearchParams的构造器函数得到params对象
// 3. 使用params对象身上的append方法进行数据的传参
// params.append(key,value)

    // 1. 先设置请求头 
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // 2. 实例化 URLSearchParams的构造器函数得到params对象
    let params2 = new URLSearchParams();
    // 3. 使用params对象身上的append方法进行数据的传参    // params.append(key,value)
    params2.append('name', 'zhanghaolin');
    params2.append('gender', 'man');
    params2.appends('age', 11);

    axios.post('../', params2)
    .then((ret) => {
            console.log(ret.data);
        })
        .catch(err => console.log(err))
        .finally(function() {

        });

    axios({
            url: ',,/',
            method: 'post',
            data: {
                name: 'zhangyu',
                gender: 'woman',
                age: '22'
            }
        })
        .then((ret) => {
            console.log(ret.data);
        })
        .catch(err => console.log(err))
        .finally(function() {

        });

解决方法

   // 1. 先设置请求头 
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // 2. 实例化 URLSearchParams的构造器函数得到params对象
    let params = new URLSearchParams();
    // 3. 使用params对象身上的append方法进行数据的传参    // params.append(key,value)
    params.append('name', 'zhangyu');
    params.append('gender', 'woman');
    params.appends('age', 22);

    axios({
            url: '../',
            methods: 'post',
            data: params,
            // headers: { //单个请求设置请求头
            //     'Content-Type': "application/x-www-form-urlencoded"
            // }
        })
        .then((ret) => {
            console.log(ret.data);
        })
        .catch(err => console.log(err))
        .finally(function() {

        });
  • my1-数据请求- axio-携带参数
<body>
    <section id="app">
        <button type="button" @click="getStatic">静态请求</button>
        <button type="button" @click="get">动态数据-- 接口-- get</button>
        <button type="button" @click="post">动态数据--接口--post</button>
    </section>
</body>
<script src="../../lib/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    Vue.prototype.$http = axios;

    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    new Vue({
        el: '#app',
        methods: {
            getStatic() {
                this.$http({
                        url: './mock/data.json',
                        methods: 'get'
                    })
                    .then(res => console.log(res))
                    .catch(err => console.log(err));
            },
            get() {
                this.$http({
                        url: 'http://localhost:3000/shop',
                        params: {
                            name: 'zhanghaoyu',
                            age: 24
                        }
                    })
                    .then(res => console.log(res))
                    .catch(err => console.log(err));
            },
            post() {
                const params = new URLSearchParams();
                params.append('name', 'zhanghaolin');
                params.append('age', 11);
                this.$http({
                        url: 'http://localhost:3000/shop',
                        method: 'post',
                        data: params
                    })
                    .then(res => console.log(res))
                    .catch(err => console.log(err));
            }
        },
    })
</script>

vue-resource

Vue1.0

Vue1.0数据请求我们使用的是一个第三方的封装库,这个封装库叫做 vue-resource
vue-resource现在已经淘汰了,它的作者也推荐我们使用axios

  • vue-resource使用形式和axios一样的
    • this.$http.get
    • this.$http.post
    • this.$http({})
    • vue-resource有jsonp方法,而axios是没有的
    • vue-resoure是vue的插件,它直接挂在了Vue原型上
<body>
    <div id="app">
        <button @click="getStatic"> 静态数据 </button>
    </div>
</body>

<script>
    new Vue({
        el: '#app',
        methods: {
            getStatic() {
                this.$http({
                        url: './mock/data.json',
                    }).then(res => console.log(res))
                    .catch(err => console.log(err))
            }
        }
    })
</script>
Vue2.0
  • axios [ 可以说是目前最好的数据请求的封装库 ]
  • fetch

fetch

fetch是原生 js 提供的
fetch也是Promise
fetch对数据是没有进行封装,有安全的问题
fetch默认get请求

 * 第一个then是对数据进行格式化
    * json() json类型数据格式户
    * text() 文本类型数据格式化
    * blob() 二进制数据格式化   图片  视频 音频 

* 第二then得到的才是格式化后的数据
1.get
    // 将一个对象转成url字符 , 用node中 url模块来完成
    fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中写上传递的参数
            method: 'GET'
        })
        .then((res) => {
            return res.text()
        })
        .then((res) => {
            console.log(res)
        })
        .catch(err => console.log(err))


2.post
* 设置请求的头信息
* 在POST提交的过程中,一般是表单提交,可是,经过查询,发现默认的提交方式是:Content-Type:text/plain;charset=UTF-8,这个显然是不合理的。下面咱们学习一下,指定头信息:
    fetch('https://www.baidu.com/search/error.html', {
            method: 'POST',
            body: new URLSearchParams([
                ["foo", 1],
                ["bar", 2]
            ]).toString(),
            headers: new Headers({
                    'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
                }) // 这里是请求对象
        })
        .then((res) => {
            return res.text()
        })
        .then((res) => {
            console.log(res)
        })
    fetch('/books/123', {
            method: 'post',
            body: JSON.stringify({
                uname: '张三',
                pwd: '789'
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(function(data) {
            return data.text();
        })
        .then(function(data) {
            console.log(data)
        });

数据请求

  1. 使用原生js提供的fetch
  2. 使用第三方封装库: axios
    • Vue中可以统一对axios进行挂载
  Vue.prototype.$http = axios
  1. fetch vs axios
    • axios 对已获得的数据进行了一层封装 XSRF
      • axios底层自动对数据进行了格式化
    • fetch并没有进行封装,拿到就是格式化后的数据
      • fetch进行了多一层的格式化
        • res.json()
        • res.blob() 格式化二进制
        • res.text()

fetch 文档
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#%E8%BF%9B%E8%A1%8C_fetch_%E8%AF%B7%E6%B1%82

fetch项目使用的博客
https://blog.csdn.net/hefeng6500/article/details/81456975




计算属性

何时使用计算属性? 具备两个条件
\1. 有逻辑
\2. 实例中直接当做全局变量处理
computed 是Vue中的一个选项

业务: 如果我们想要让一个字符串反向,应该如何操作?
1. 部分逻辑操作
字符串 -》 数组 -》 反向 -》 字符串
2. 思考: 这部分逻辑操作往哪里写?
- methods 更适合用户交互
- 直接写在mustache里面

以上方案,我们发现将逻辑交给了v做,有点违背了关注点分离 

新的方案
    1. 能写逻辑,逻辑要放在vm
    2. mustache里面更希望得到的事一个**类似全局变量的内容**

Vue提供的方案叫做  计算属性

Vure里面默认处理了computed里面的方法调用,我们直接写计算属性名称即可,不需要加()
<body>
    <div id="app">
        <p> 没有反向: {{ info }} </p>
        <p> {{ info.split('').reverse().join('') }} </p>
        <p> 反向字符: {{ reserseInfo }} </p>
    </div>
</body>
<script src="../../lib/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            info: '你很美丽'
        },
        computed: {
            //这里面放的都是方法
            reserseInfo () {
                return this.info.split('').reverse().join('')
            }
        }
    })
</script>

侦听属性

侦听属性【 监听 】 - watch
1. 和data选项有关

  • 项目中如何选择
    1. 如果是事件处理程序: 方法
    2. 如果是由某一个数据改变引起新的异步数据请求,那么我们可以watch
    3. 如果有逻辑处理,但是将来使用类似于变量,那么我们选择计算属性
<body>
    <div id="app">
        姓:<input type="text" v-model = "firstName"> <br>
        名:<input type="text" v-model = "lastName"> <br>
        全名:<input type="text" v-model = "fullName"> <br>
    </div>
</body>
<script src="../../lib/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            firstName: '',
            lastName: '',
            fullName: ''
        },
        watch: {
            //watch是一个对象
            // watch里面存储的类型: 方法,对象,普通字符
            firstName ( val ) {//方法的名称和data选项中的key相同,是谁就监听谁
                console.log( val )
                console.log('firstName发生了改变')
                this.fullName = val + this.lastName
            },
            lastName ( val ) {
                this.fullName = this.firstName + val 
            }
        }
    })
</script>

mock.js

node.js文件,用于生成mock模拟数据

const Mock = require('mockjs');
const fs = require('fs');
const path = require('path')

const data = Mock.mock({
    // 字段: 字段内容
    //     list 字段
    //     | 管道符
    //     1 - 10 表示随机生成 1条 - 10条数据 
    //     3
    //     +1 表示自增
    'list|3': [{
        'id|+1': 1,
        'name|+1': ['张三', '李四', '王五']
    }]
})

fs.writeFile(path.join(__dirname, 'data.json'), JSON.stringify(data), (err) => {
    if (err) return console.log('写入文件失败!' + err.message) // 如果文件写入失败,则报错
    console.log('文件写入成功!')
})

侦听属性 vs 计算属性 vs 方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值