作用
ref用来定义:基本类型数据、对象类型数据;
建议:基本类型数据用ref来定义;对象类型数据用reactive定义
ref定义的数据是响应式;
ref定义基本类型数据
Student.vue
<template>
<div><h2>{{ name }}</h2><h2>{{ age }}</h2><button @click="updateName">修改名字</button><button @click="updateAge">修改年龄</button><button @click="showPhone">显示联系方式</button>
</div>
</template><script setup lang="ts" name="Student">import { ref, Ref } from 'vue';let name=ref('weihu')let age=ref(18)function updateName(){name.value="李四"}function updateAge(){age.value+=1}function showPhone(){alert("18880709")}
</script><style scoped></style>
ref定义对象类型数据
Student.vue
<template>
<div><h2>ref定义对象类型数据</h2><h2>{{ studentInfo.name }}</h2><h2>{{ studentInfo.age }}</h2><button @click="updateName">修改名字</button><button @click="updateAge">修改年龄</button><button @click="showPhone">显示联系方式</button>
</div>
</template><script setup lang="ts" name="Student">import { ref, Ref } from 'vue';let studentInfo=ref({name:'weiwei',age:18})function updateName(){studentInfo.value.name="李四"}function updateAge(){studentInfo.value.age+=1}function showPhone(){alert("18880709")}
</script><style scoped></style>