欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

vue3 ref函数 有大用

我们知道,在vue3.0引入了composition API,setup函数是其核心函数

setup函数中,可以使用ref函数,用于创建一个响应式数据,当数据发生改变时,Vue会自动更新UI
例如:使用ref函数定义一个变量count

  1. import { ref } from 'vue';
  2. function useChangeCount() {
  3. let count = ref(0);
  4. function change_count() {
  5. count.value += 1;
  6. }
  7. return { count, change_count }
  8. }
  9. export default useChangeCount;

然后在组件中引入该模块:import useChangeCount from "./composition_tiny_js/count"
并且在组件的setup中使用,并通过return的形式将外界需要用到的变量和函数暴露出去

  1. setup() {
  2. let { count, change_count } = useChangeCount();
  3. return { count, change_count };
  4. }

这样上面暴露的count变量,change_count方法就可以在外界使用了

  1. <template>            
  2. <div>            
  3. <h1>{{ count }}</h1>            
  4. <button @click="change_count">点我</button>            
  5. </div>            
  6. </template>            

需要注意的是:

  1. setup中定义的变量或方法,都必须通过return {xxx,xxx}暴露出去,外界才能使用

  2. ref函数仅能监听基本类型的变化,不能监听复杂类型的变化(比如对象、数组)

以上就是ref函数的基本使用!

来自  https://blog.csdn.net/lhjuejiang/article/details/114675890




vue3 ref函数用法



1.在setup函数中,可以使用ref函数,用于创建一个响应式数据,当数据发生改变时,Vue会自动更新UI

  1. <template>
  2.     <div>
  3.         <h1>{{mycount}}</h1>
  4.         <button @click="changeMyCount">changeMyCount</button>
  5.     </div>
  6. </template>
  7. <script>
  8. import { ref } from "vue";
  9. export default {
  10.     name: "ref",
  11.     setup(){
  12.         const mycount = ref(2);
  13.         const changeMyCount = ()=>{
  14.             mycount.value = mycount.value + 2 ;
  15.         }
  16.         
  17.         return {
  18.             mycount,
  19.             changeMyCount,
  20.         }
  21.     }
  22. };
  23. </script>

ref函数仅能监听基本类型的变化,不能监听复杂类型的变化(比如对象、数组)
监听复杂类型的变化可以使用reactive函数

2.通过ref属性获取元素
vue3需要借助生命周期方法,在setup执行时,template中的元素还没挂载到页面上,所以必须在mounted之后才能获取到元素。

  1. <template>
  2.     <div>
  3.         <div ref="box"><button>hehe</button></div>
  4.     </div>
  5. </template>
  6. <script>
  7. import { ref } from "vue";
  8. export default {
  9.     name: "ref",
  10.     setup(){
  11.         const box = ref(null)
  12.         onMounted(()=>{
  13.             console.log(box.value)
  14.         })
  15.     }
  16. };
  17. </script>

 

来自 https://blog.csdn.net/wuxing164/article/details/109800885


普通分类: