初探vue composition api
只是简单的以为ref
适用于js基本数据类型,而reactive
适用于引用数据类型,直到我写demo想整体替换一个对象obj2时,怀疑了人生,源代码:
<template>
<div class="about">
<h1>This is an about page</h1>
<p>
<span>{{ obj1.fruit }}</span>
<button @click.prevent="updateObj1">更新1</button>
</p>
<p>
<span>{{ fruit }} -- {{ animal }}</span>
<button @click="updateObj2">更新2</button>
</p>
</div>
</template>
<script>
import { ref, toRefs, reactive, onMounted } from 'vue'
// 修改对象1
function useObject1() {
let obj1 = reactive({ fruit: 'apple' })
let updateObj1 = () => obj1.fruit = obj1.fruit == 'apple' ? 'banana' : 'apple'
return {
obj1,
updateObj1
}
}
// 修改对象2
function useObject2() {
let obj2 = reactive({ fruit: 'apple', animal: 'monkey' })
let updateObj2 = () => obj2 = { fruit: 'pear', animal: 'snake' }
return toRefs(obj2)
}
export default {
name: 'About',
setup(props, context) {
const { obj1, updateObj1 } = useObject1()
const { fruit, animal } = useObject2()
onMounted(() => {
console.log('onMounted')
})
return {
obj1,
updateObj1,
fruit,
animal
}
}
}
</script>
代码很简单,修改obj1的属性时使用obj1.属性=新值没有问题
但是,修改obj2的时候遇到了问题,整个obj2被替换后,更新的函数没有用武之地了。。。
无果,只能奔全球最大“同性交友网站”了,提了个issues,好吧,问问题还是去专业的问问题网站提问吧--
按照issues,很顺畅的就解决了
<template>
<div class="about">
<h1>This is an about page</h1>
<p>
<span>{{ obj2.fruit }} -- {{ obj2.animal }}</span>
<button @click="updateObj2">更新2</button>
</p>
</div>
</template>
<script>
import { ref, toRefs, reactive, onMounted } from 'vue'
// 修改对象2
function useObject2() {
let obj2 = ref({ fruit: 'apple', animal: 'monkey' })
let updateObj2 = () => {
obj2.value = { fruit: 'pear', animal: 'snake' }
}
return {
obj2,
updateObj2
}
}
export default {
name: 'About',
setup(props, context) {
const { obj2, updateObj2 } = useObject2()
onMounted(() => {
console.log('onMounted')
})
return {
obj2,
updateObj2
}
}
}
</script>
所以,ref
和reactive
并不是用来区分基本数据类型和引用数据类型的,反而他们的功能是一样的,只不过适用场景不太一样,了解这点之前先看下下面的代码:
// 风格1
let age = 10
let name = 'zhangsan'
function updatePerson() {
age = 20
}
// 风格2
let person = {
age: 10,
name: 'zhangsan',
sex: 'male'
}
function updatePerson() {
person.age = 20
}
以上两种写法其实都对,只不过适用的写代码的风格不太一样,ref
和reactive
的区别就分别类似上面的风格1和风格2:
// ref
let age = ref(10)
let name = 'zhangsan'
// reactive
let person = reactive({
age: 10,
name: 'zhangsan'
})
了解了这些,之后再使用ref
和reactive
就不会有疑惑啦~
完