Skip to content

一、响应式基础

一、ref

(1)script标签中使用

javascript
import { ref } from 'vue'

const count = ref(0)

console.log(count) // { value: 0 }
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

(2)template标签中使用

html
<button @click="increment">
  {{ count }}
</button>

(3)整体使用

vue
<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">
    {{ count }}
  </button>
</template>

二、reactive

(1)script标签中使用

javascript
import { reactive } from 'vue'

const state = reactive({ count: 0 })

(2)template标签中使用

html
<button @click="state.count++">
  {{ state.count }}
</button>

(3)局限性

提示

1、只适用于对象类型 (对象、数组和如 Map、Set 这样的集合类型)

2、不能替换整个对象