美文网首页
vue3—reactive如何更改属性

vue3—reactive如何更改属性

作者: 一个给予者 | 来源:发表于2021-05-27 17:34 被阅读0次

    vue3新增了响应性API,其中数据有两种,refreactive
    reactive支持非原始对象,基础类型不能使用(Number,Boolean等)

    例1

    const obj = reactive({ count: 0 })
    obj.count++
    console.log(obj.count) // 1
    
    const obj = reactive([])
    obj.push(1)
    console.log(obj) // [1]
    

    注意:使用let定义后不能直接重新赋值reactive对象,会导致响应式的代理被覆盖。

    例2

    export default {
      name: 'App',
      setup() {
        let obj = reactive({a:1})
        // 不能这么写,这样重新赋值后会,obj会变成普通对象,失去响应式的效果;
        setTimeout(() => {
          obj = {a:2,b:3}
        }, 1000)
        return {
          obj
        }
      }
    }
    

    遇到这样的情况,需要单独赋值
    例3

    const obj = reactive({a:1})
    setTimeout(() => {
      obj.a = 2;
      obj.b = 3;
    }, 1000)
    
    

    或者使用Object.assign
    例4

    export default {
      name: 'App',
      setup() {
        const obj = reactive({a:1})
        setTimeout(() => {
          Object.assign(obj,{a:2, b:3})
        }, 1000)
        return {
          obj
        }
      }
    }
    

    案例地址

    相关文章

      网友评论

          本文标题:vue3—reactive如何更改属性

          本文链接:https://www.haomeiwen.com/subject/ioddsltx.html