vue3中的ref数据响应式

75 阅读1分钟

· 作用: 定义一个数据的响应式

· 语法: const xxx = ref(initValue):

 创建一个包含响应式数据的引用(reference)对象

js中操作数据: xxx.value

(html)模板中操作数据: 不需要.value

<template>
  <div style="font-size: 14px;">
    <h2>{{count}}</h2>
    <hr>
    <button @click="update">更新</button>
  </div>
</template>

<script lang="ts">
// vue3版本语法
import { defineComponent, ref } from 'vue'
export default defineComponent({

  /* 在vue3中依然可以使用data和methods配置, 但建议使用其新语法实现 */
  // data () {
  //   return {
  //     count: 0
  //   }
  // },
  // methods: {
  //   update () {
  //     this.count++
  //   }
  // }

  /* 使用vue3的composition API */
  setup () {
    // 定义响应式数据 ref对象
    const count = ref(1)
    console.log(count)
    // 更新响应式数据的函数 js里使用时需要加.value
    function update () {
      console.log('update',count)
      count.value = count.value + 1
    }

    return {
      count,
      update
    }
  }
})
</script>

页面初始显示效果:

image.png

点击更新按钮后显示效果:

image.png