Vue

ref

ref 接受一个 inner value,然后返回一个响应式且可变的ref对象,这个ref对象需要使用.value来访问其inner value

const foo = ref('foo')
console.log(foo.value) // 'foo'
foo.value = 'bar'
console.log(foo.value) // 'bar'

示例

<template>
  <div>
    <button @click="increase">被点击了{{count}}次</button>
  </div>
</template>
<script>
  import { createComponent, ref } from '@vue/composition-api'
  export default createComponent({
    setup() {
      // 声明一个名为count,初始值为0的ref对象
      const count = ref(0)
      const increase = () => {
        // 每次点击按钮count值+1,特别需注意的是,需要'.value',才能访问到count的inner value。
        count.value++
      }
      return {
        count,
        increase
      }
    }
  })
</script>

当在 template 或者 render 函数 中访问ref时,它的inner value会被自动解包,不需要在 template 中添加.value

  • 在 Reactive 对象里存取

当一个ref被作为reactive 对象的属性时被存取或者变更时,它会自动的解包inner value,可以像正常的属性一样去使用它。

const count = ref(0)
const state = reactive({
  count
})
// 访问count
console.log(state.count) // 0
// 变更count
state.count = 1
console.log(count.value) // 1
  • 注意,如果一个新的 ref 对象被分配给一个带有 ref 的属性,它将会替换旧的 ref。
....
const otherCount = ref(2)
//旧的count,被otherCount替代,
state.count = otherCount
console.log(state.count) // 2
console.log(count.value) // 1

你真棒,到了这里,你已经掌握了利用reactiveref来给项目创建响应式的对象,累了的话,喝杯茶,在继续战斗吧。

下一节:用来检测一个值是否是一个ref对象。当需要解构一个或许为ref对象时,尤其有用。