学习vue3系列reactive

vue3响应式API有ref和reactive,今天主要讲解reactive函数。

 <template>
  <h1>{{ msg }}</h1>
  <button @click="change">count is: {{ state.count }}</button>
</template>


<script>
import { ref, reactive } from 'vue'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup(){
    let state = reactive({count: 0})
    const change = () => state.count++
    return { state, change }
  }
}
</script>

reactive 接收一个普通对象然后返回该普通对象的响应式代理。等同于 2.x 的 Vue.observable()。

响应式转换是“深层的”:会影响对象内部所有嵌套的属性。基于 ES2015 的 Proxy 实现,返回的代理对象不等于原始对象。建议仅使用代理对象而避免依赖原始对象。

不要解构返回的代理对象,那样会使其失去响应性:

 <template>
  <h1>{{ msg }}</h1>
  <button @click="change">count is: {{ count }}</button>
</template>


<script>
import { ref, reactive } from 'vue'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup(){
    let state = reactive({count: 0})
    const change = () => state.count++
    return { ...state, change } // 展开state属性将失去响应式
  }
}
</script>

那如果我们真的想展开state的属性,在模板使用count而不是state.count的写法那怎么办呢?我们可以使用toRef和toRefs这两个API,进行转换成ref对象,之前已经介绍了ref对象是可以直接在模板中使用的。

 

<template>
  <h1>{{ msg }}</h1>
  <button @click="change">count is: {{ count }}</button>
</template>


<script>
import { ref, reactive, toRef } from 'vue'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup(){
    let state = reactive({count: 0})
    const change = () => state.count++
    let countRef = toRef(state, 'count')
    return { count: countRef, change }
  }
}
</script>

toRef 可以用来为一个 reactive 对象的属性创建一个 ref。这个 ref 可以被传递并且能够保持响应性。

 

<template>
  <h1>{{ msg }}</h1>
  <button @click="change">count is: {{ count }}</button>
</template>


<script>
import { ref, reactive, toRef } from 'vue'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup(){
    let state = reactive({count: 0})
    const change = () => state.count++
    let stateAsRefs = toRefs(state)
    return { ...stateAsRefs, change }
  }
}
</script>

把一个响应式对象转换成普通对象,该普通对象的每个 property 都是一个 ref ,和响应式对象 property 一一对应。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值