Vue Component ref绑定问题

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.

vue自从集成了ts后,相信诸多的开发者都是深受折磨。不是刨根到底的情况下真的是多余的不能在多余。但是作为一名开发者,你又无法无视那些警告。

发生这个报错的核心是我封装了动态组件,动态组件内部的绑定又是使用的ref。
起初一直以为是是组件内部问题。所以一直在twInput这个文件排错,如下图


image.png

下面是错误代码:


image.png

image.png

改的过程其实也非常简单:

//这里用ref的话,vue给出警告Vue接收到一个组件,该组件被制成反应对象。这可能会导致不必要的性能开销,应该通过将组件标记为“markRaw”或使用“shallowRef”而不是“ref”来避免。
// 如果使用 markRaw 那么currentComp将不永远不会再成为响应式对象。 所以得使用 shallowRef
// ref 替换成 shallowRef。跟报警告的意思是一样的。
let objComponent= shallowRef({
    'twInput': twInput,
    'select': TwSelect,
    'date': twDate,
    'time': twTime,
    'switch': twSwitch,
    'checkbox': twCheckbox,
    'radio': twRadio,
})

component 绑定ref

<div v-for="item in list" :ref="setItemRef"></div>
const setItemRef = el => {
      if (el) {
        itemRefs.push(el)
      }
    }

这里存在单独命名的场景可以反向处理。因为ref内部不支持$event或event传递,所以可以在内部组件定义好名称比如

const setItemRef = (el) => {
    if (el) {
        switch (el.val) {
            case 'cars':
                carsRef = el
                break;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容