vue的数据请求、计算属性、侦听属性、mixin、虚拟dom

数据请求

### 数据请求在前端开发中的使用有两种形式

  1. 使用原生javascript提供的数据请求
  • ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )
  • fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )
    • 使用格式:
  1. 使用别人封装好的第三方库
    目前最流行的,使用率最高的是 axios

vue中我们最常使用的

  1. vue
    1.x 的版本提供了一个封装库 vue-resource , 但是到了vue
    2.x版本之后,这个就弃用了
    vue-resource使用方法和 axios 相似度在 95%
    vue-resouce有jsonp方法,但是axios是没有的

  2. vue2.x版本我们最用使用的数据请求是 axios 和 fetch

数据请求的类型

get 常用
post常用
head
put
delete
option

axios vs fetch

axios得到的结果会进行一层封装,而fetch会直接得到结果

举例:
axios

    {data: 3, status: 200, statusText: "OK", headers: {}, config: {},}
    config: {adapter: ƒ, transformRequest: {}, transformResponse: {}, timeout: 0, xsrfCookieName: "XSRF-TOKEN",}
    data: 3
    headers: {content-type: "text/html; charset=UTF-8"}
    request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,}
    status: 200
    statusText: "OK"
    __proto__: Object

fetch

fetch()
new Vue({
  el: '#app',
  methods: {
    get () {
      // console.log(fetch('http://localhost/get.php?a=1&b=2')) // Promise
      fetch('http://localhost/get.php?a=1&b=2') // Promise
        .then( res => res.text()) //对数据进行格式化
        .then( data => console.log( data ))
        .catch( error => {
          if( error ) throw error 
        })
    },


    post () {
      fetch( 'http://localhost/post.php',{
        method: 'POST',
        headers: new Headers({ //解决跨域
          'Content-Type': "application/x-www-form-urlencoded"
        }),
        body: new URLSearchParams([  // 进行参数的修改
          ["a",1],
          ["b",2]
        ]).toString()
      })
        .then( res => res.text() ) // res.json()   res.blob() 不常用
        .then( data => console.log( data ))
        .catch( error => {
          if( error ) throw error 
        })
    },



    json () {
      fetch('./data/data.json')
        .then( res => res.json())
        .then( data => console.log( data ))
        .catch( error => {
          if( error ) throw error 
        })
    }
  }
})

Axios总结
1.get方法

A: 无参数
    axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
B: 有参数
    axios({
        url: 'http://xxx',
        method: 'get' //默认就是get,这个可以省略,
        params: {
            key: value
        }
    })

2.post
    注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑
    解决步骤: 
            1. 先设置请求头 
            2. 实例化 URLSearchParams的构造器函数得到params对象
            3. 使用params对象身上的append方法进行数据的传参

// 统一设置请求头

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
let params = new URLSearchParams()

// params.append(key,value)

params.append('a',1)
params.append('b',2)

axios({
    url: 'http://localhost/post.php',
    method: 'post',
    data: params,
    headers: {  //单个请求设置请求头
       'Content-Type': "application/x-www-form-urlencoded"
    }
})
.then(res => {
    console.log( res )
})
.catch( error => {
    if( error ){
    throw error
}
})


Fetch
1.get

fetch('http://localhost/get.php?a=1&b=2')
    .then(res=> res.text()) // 数据格式化 res.json() res.blob()
    .then(data => {
        console.log( data )
    })
    .catch(error => {
        if( error ){
        throw error
    }
})

注意事项:
A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
Object --> String
B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据
格式化处理方式有
fetch(’./data.json’)
.then(res=>{
res.json() //res.text() res.blob()
})
.then( data => console.log(data))
.catch( error => console.log( error ))

2.post
fetch文档
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#进行_fetch_请求

fetch请求博客
https://blog.csdn.net/hefeng6500/article/details/81456975

模拟假数据

  1. mock.js
  2. json-server( 启动一个api接口服务器 )

computed 计算属性
案例: 为什么vue中要使用计算属性?
让一个字符反向
分析:

{{ msg.split(’’).reverse().join(’’) }}


上面代码的写法,有些违背关注点分离,而且会让我们的DOM结构看起来不简洁
        解决方案:
          从上面的案例得出两个结论:
            1. 我们的使用结果是要想data选项中定义的数据一样直接使用,那就是最好的
            2. 我们还必须需要一定的逻辑支撑,一想到逻辑,那我们就想到了函数

          综上: vue这边提出来一个新的解决方案就是: 计算属性

        在项目中, 使用时候使用计算属性呢?
          只要满足一下两个条件:
            1. 有逻辑处理
            2. 像变量一个使用

        总结: 计算属性一定要有返回值

      computed  vs  methods 
        -计算属性是基于它们的依赖进行缓存的。
        -计算属性只有在它的相关依赖发生改变时才会重新求值
      */
    new Vue({
            data: {
                msg: ' my name is yyb '
            },
            computed: {
                //这里存放的是多个方法,这些方法往往都和data选项中的数据有关系
                reverse_msg() {
                    return this.msg.split('').reverse().join('')
                }
            }
        }).$mount('#app') // 手动挂载app模板
        ```




  watch 侦听属性
      1. 是用来监听 data 选项中的数据的,只要data中的数据发生改变,它就会自动触发
      2. watch是一个对象,它里面存储的是 { [key: string]: string | Function | Object | Array }
      3. 往往watch我们里面常存储的是方法
      4. watch中方法的名称就是 data 选项中数据的名称
      5. 深度监听
        watch: {
          num: {
            deep: true,
            handler () {
              //数据改变之后执行的事情
            }
          }
        }
  */
  new Vue({
    el: '#app',
    data: {
      msg: ' hello ',
      num: 100
    },
    watch: {
      msg () { // 方 法
        console.log('msg这条数据发生了改变')
      },
      num: {
        deep: true,
        handler () {
          console.log( 'num 发生了改变' )
        }
      }
    }
  })



  mixin
          使用它的好处: 
            1. 将 options 中的配置项可以单独抽离出来,单独管理,这样方便维护
          使用:
            1. 新建一个对象用来保存 options 中某一个配置项,比如: methods
            2. 接下来要将我们创建好的对象混入到我们的 ViewModel 中,我们的混入形式有两种
                - 局部混入 【 推荐 】
                  只是在当前  vm 中才有
                  new Vue({
                    mixins: [ myMixin ]
                  })
                - 全局混入
                  在所有的vm中都会有

                  Vue.mixin({
                    methods: {
                      aa () {}
                    }
                  })
      */

  Vue.mixin({
        methods: {
            aa() {
                console.log('aa')
            }
        }
    })

    var my_methods = {
        methods: {
            increment() {
                console.log('增加')
            }
        }
    }

    var vm = new Vue({
        el: '#app',
        data: {},
        // methods: {},
        watch: {},
        computed: {},
        mixins: [my_methods] //局部混入
            // ....非常多
    })


virtual dom 

      总结: 
        根据刚才书写的案例我们得知了:
          1. 越多的真实dom操作,越损耗性能
          2. 操作数据要大大的减少性能损耗,提高渲染效率

        --> 能不能 创建以个树形结构( 对象表示 )来表示一个DOM结构呢? --》 虚拟DOM  

        VDOM的渲染流程
          1. 获取数据
          2. 根据数据创建VDOM (相当于给对象赋值)
          3. 根据VDOM渲染生成真实DOM ( 根据createElmeent('DIV') ) 
          4. 当数据发生改变后,又会生成新的VDOM
          5. 通过 diff 算法 比对 多次生成的 VDOM, 将不同的内容比对出来,然后在进行真实DOM渲染,
              一样的内容是不会进行渲染的,这就是VDOM'就地复用' | '惰性原则'
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值