码迷,mamicode.com
首页 > 其他好文 > 详细

vue实用方法函数

时间:2021-06-18 19:35:53      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:添加   rop   更新   因此   ons   proc   log   作用   mit   

及时渲染视图的方法

有时候遇到给一个数组或者对象添加值或修改值,页面并不会及时渲染出修改过的数据,这时可以实用this.$set来解决这个问题

在使用this.$set(target, key, value)时,target为需要添加属性的对象,key是要添加的属性名,value为属性key对应的值。

在使用this.$set(target.name, key, value)时,target为需要修改属性的对象,key是要修改的属性名,value为属性key对应的值。

下面是set源码

// src/core/observer/index.js
export function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== ‘production‘ &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== ‘production‘ && warn(
      ‘Avoid adding reactive properties to a Vue instance or its root $data ‘ +
      ‘at runtime - declare it upfront in the data option.‘
    )
    return val
  }
  if (!ob) {
    target[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

等待数据更新之后的dom操作

有时候我们需要数据加载好之后才更新dom,比如下拉抽屉,高度未知,但css动画效果需要获取到整个下拉抽屉的高度,这时就需要加载完数再更新dom,从而可以获得它的高度

<template>
    <button ref="tar" @click="testClick">{{content}}</button>
</template>
 
<script>
    export default {
        data () {
            return {
                content: ‘初始值‘
            }
        }
     methods: {
       testClick(){
         this.content = ‘改变了的值‘
         // 这时候直接打印的话,由于dom元素还没更新
         // 因此打印出来的还是未改变之前的值
         console.log(that.$refs.tar.innerText) // 初始值
       }
     }
    }
</script>

this.$nextTick这个方法作用是当数据被修改后使用这个方法会回调获取更新后的dom再渲染出来

methods:{
    testClick() {
        this.content = ‘改变了的值‘
        this.$nextTick(() => {
            // dom元素更新后执行,因此这里能正确打印更改之后的值
            console.log(that.$refs.tar.innerText) // 改变了的值
        })
    }
}

也就是延迟了console.log的触发时间,有点类似于定时器,你先等等,等我把数据更新了你再打印,可以方便一些操作

vue实用方法函数

标签:添加   rop   更新   因此   ons   proc   log   作用   mit   

原文地址:https://www.cnblogs.com/black-eyes/p/14898112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!