验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

vue3使用ref的性能警告问题怎么解决

阅读:758 来源:乙速云 作者:代码code

vue3使用ref的性能警告问题怎么解决

      vue3使用ref的性能警告

      问题

      使用 ref 的性能警告 代码如下

      
      
      
      
      import { ref,shallowRef } from "vue";
      import TodoList from "./components/TodoList.vue";
      import Rate from "./components/Rate.vue";
      
      let tabs ={
        TodoList,
        Rate
      }
      let currentTabComponent = ref(TodoList)
      

      警告

      runtime-core.esm-bundler.js:6591 [Vue warn]: Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with markRaw or using shallowRef instead of ref. Component that was made reactive:
      译文:
      runtime-core.esm-bundler.js:6591 [Vue 警告]:Vue 收到一个组件,该组件已成为响应式对象。这会导致不必要的性能开销,应该通过使用 markRaw 标记组件或使用 shallowRef 代替 ref 来避免。被响应的组件:

      • markRaw: 标记一个对象,使其永远不会转换为 proxy。返回对象本身。

      • shallowRef: 创建一个跟踪自身 .value 变化的 ref,但不会使其值也变成响应式的。

      解决

      我通过将对象标记为shallowRef解决了这个问题

      因此,不要将组件存储在您的状态中,而是存储对它的键控引用,并针对对象进行查找

      完整代码

      
      
      
      
      import { ref,shallowRef } from "vue";
      import TodoList from "./components/TodoList.vue";
      import Rate from "./components/Rate.vue";
      
      let tabs ={
        TodoList,
        Rate
      }
      let currentTabComponent = shallowRef(TodoList)
      
      function fn (tab){
        currentTabComponent.value = tabs[tab]
      }
      

      vue3 ref函数用法

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

      
       
      

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

      监听复杂类型的变化可以使用reactive函数

      2.通过ref属性获取元素

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

      
       
      
    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>