多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 1. ref 创建响应式数据 * `ref`是一个函数,返回的是一个`Ref`对象。 * 作用:用来定义一个响应式的数据。 * 一般用来定义一个基本类型的响应式数据,如果想要定义一个对象类型的响应式数据可以使用函数`reactive`。 ```html <template> <!-- 6. 在模板中调用count的值,直接调用count即可,不能调用count.value --> <h1>{{ count }}</h1> <button @click="updateCount">更新count</button> </template> <script lang="ts"> // 1. 引入 ref 函数 import { defineComponent, ref } from "vue"; export default defineComponent({ setup() { // 2. 调用 ref 函数定义一个响应数据 const count = ref(0); // 3. 定义一个更新count属性的方法 function updateCount() { count.value++; // 4. 在js代码中以 count.value 调用来获取count的值 console.log(count.value); } return { // 5. 将他们放置在setup的返回对象中 count, updateCount, }; }, }); </script> ``` ![](https://img.kancloud.cn/f3/8b/f38bcb8906320a0107777ffc336b6f77_1006x172.gif) <br/> # 2. ref 获取页面元素 `ref`函数可以获取页面中已经加载完毕的元素。 ```html <template> <!-- 1. 在标签中使用 ref 属性绑定一个数据 --> <input type="text" id="demo" ref="inputRef" /> </template> <script lang="ts"> import { defineComponent, onMounted, ref } from "vue"; export default defineComponent({ setup() { //2. 调用ref创建初始值为null的响应数据 const inputRef = ref < HTMLElement | null > (null); onMounted(() => { //3. 在生命周期函数onMounted页面已经渲染好了,可以在这里拿到页面的元素 console.log(inputRef.value); //<input type="text" id="demo"> //表示标签存在时,就让该标签自动获取焦点 inputRef.value && inputRef.value.focus(); }); return { inputRef, }; }, }); </script> ```