• ref 使用 aaa.value
  • reactive 类型是 object

ref 和 reactive 一个针对原始数据类型,而另一个用于对象,这两个API都是为了给JavaScript普通的数据类型赋予响应式特性(reactivity)。

  • reactive和ref都是用来定义响应式数据的,而reactive更推荐用来定义对象,ref更推荐定义基础数据类型,但是ref也可以定义数组和对象
  • 在访问数据的时候,ref需要使用.value,而reactive不需要
1
const dataAsRefs = toRefs(data);

步子比蛋大

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div>Hello, {{ name }}!</div>
<input v-model="name" />
<button :disabled="!isNamePresent" @click="submitName">Submit</button>
</template>

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

const name = ref('')
const isNamePresent = computed(() => name.value.length > 0)

function submitName() {
console.log(name.value)
}
</script>

父子组件

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- Form.vue -->
<template>
<form @submit.prevent="submitHandler">
<label>Name
<input type="text" />
</label>
<button>Submit</button>
</form>
</template>

<script setup>
function submitHandler() {
// Do something
}
</script>

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- App.vue -->
<template>
<div>Hello, {{ name }}!</div>
<Form />
</template>

<script setup>
import { ref } from 'vue'
import Form from './components/Form.vue'

const name = ref('')

function submitForm() {
console.log(name.value)
}
</script>

defineProps 和 defineEmits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!-- Form.vue -->
<template>
<form @submit.prevent="submitHandler">
<label>Name
<input v-model="name" type="text" />
</label>
<button>Submit</button>
</form>
</template>

<script setup>
import { computed } from 'vue'
const props = defineProps({
modelValue: {
type: String,
default: ''
}
})
const emit = defineEmits(['update:modelValue', 'submit']);

const name = computed({
get () {
return props.modelValue
},
set(val) {
emit('update:modelValue', val);
}
})

function submitHandler() {
emit('submit')
}
</script>

<!-- App.vue -->
<template>
<div>Hello, {{ name }}!</div>
<Form v-model="name" @submit="submitForm" />
</template>

<script setup>
import { ref } from 'vue'
import Form from './components/Form.vue'

const name = ref('')

function submitForm() {
console.log(name.value)
}
</script>