网络上对这两个方法的争论还是不少的,但到目前为止,还没有什么实质性的理论到底是用Ref()好还是reactive()好,
也就是两种方法都可以。他们的作用都是生成响应式对象,目前来看只是编写上有所不同。我个人更倾向于使用reactive()
先看ref的使用:要在template中使用的变量,必须用ref包装一下
<template>
<div class="home">
<button v-for="(car, index) in cars" :key="index" @click="selectFun(car)">
{{ car }}
</button>
<div>选择的是{{ selectCar }}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "Home",
setup() {
const cars = ref(["EVO", "STI", "GTR"]);
const selectCar = ref("");
const selectFun = (car: string) => {
selectCar.value = car;
};
return {
cars,
selectCar,
selectFun,
};
},
components: {},
});
</script>
<style lang="scss" scoped>
.home {
margin-top: 40px;
}
</style>
reactive的使用
<template>
<div class="about">
<button
@click="data.selectFun(car)"
v-for="(car, index) in data.cars"
:key="index"
>
{{ car }}
</button>
<div>选择的是{{ data.selectCar }}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive } from "vue";
export default defineComponent({
name: "about",
setup() {
const data = reactive({
cars: ["EVO", "STI", "GTR"],
selectCar: "",
selectFun: (car: string) => {
data.selectCar = car;
},
});
return {
data,
};
},
components: {},
});
</script>
<style lang="scss" scoped>
.about {
margin-top: 80px;
}
</style>
我们在使用中主要的区别就是
- 使用
ref
时,每一个在template
中使用的属性与方法都需要使用ref
包裹,都需要在return
中返回。另外赋值时都需要使用.value
进行赋值 - 使用
reactive
时,在reactive
中把属性于方法都定义好,在return
中整体返回,另外在赋值是不在需要加上.value
,直接给对应的属性赋值即可,但在template
或者js
中使用时需要在前加上对象的属性进行调用或赋值,例如上面的data.
。template中,每次输出变量前面都要加一个data,这是可以优化的。要解决这个问题,需要使用 Vue3 的一个新函数toRefs()
。将在接下来的文章中提到。