
reactive:将平常的一个对象转换成响应式对象。所谓的响应式对象就是当页面点击修改此对象时,页面无需刷新而在页面上的其他地方有用到这个对象的地方会自动同步修改过来例如:
<template><div class="container"><div>{{obj.name}}</div><div>{{obj.age}}</div><button @click="updateName">修改数据</button></div>
</template>
<script setup>
import { reactive, toRef, toRefs } from 'vue'const obj = reactive({name: 'ls',age: 10})const updateName = () => {obj.name = "lisi"}</script>
<style scoped lang="less"></style>
当点击修改时名字会变成lisi,如果不加reactive()则不是响应式对象,即修改的时候页面数据不会改变
toref:将响应式对象中的一个属性变成响应式属性,相当于单列出来一个数据但是这个数据的值还和原响应式对象的值关联在一起。修改其值需要额外添加一个.value即对其.value进行修改才有效。例如:
<template><div class="container"><div>{{name}}</div><div>{{obj.name}}</div><div>{{obj.age}}</div><button @click="updateName">修改数据</button></div>
</template>
<script setup>
import { reactive, toRef, toRefs } from 'vue'const obj = reactive({name: 'ls',age: 10})const name = toRef(obj, "name")const updateName = () => {name.value = "lisi"}</script>
<style scoped lang="less"></style>
torefs:是将响应式对象中的所有的属性变成单独的响应式数据而且也和院对象中的值相关联着。例如:
<template><div class="container"><div>{{name}}</div><div>{{age}}</div><div>{{obj.name}}</div><div>{{obj.age}}</div><button @click="updateName">修改数据</button></div>
</template>
<script setup>
import { reactive, toRef, toRefs } from 'vue'const obj = reactive({name: 'ls',age: 10})const {name, age} = toRefs(obj)const updateName = () => {age.value = 200name.value = "lisi"}</script>
<style scoped lang="less"></style>
ref主要是用来定义单独的一个数据(非对象)为响应式数据。例如:
<template><div class="container"><div>{{name}}</div><div>{{age}}</div><button @click="updateName">修改数据</button></div>
</template>
<script setup>
import { reactive, toRef, toRefs, ref } from 'vue'let name = ref("jjw")let age = ref(0)const updateName = () => {age.value = 200name.value = "lisi"}</script>
另外ref还可以用在标签上边(另议)