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 一一对应。