繁体   English   中英

如何在 Vue 3 中向嵌套的 vanilla DOM 元素添加响应式数据?

[英]How to add reactive data to nested vanilla DOM elements in Vue 3?

如何在运行时向 DOM 元素添加响应式数据? 我无法将这些元素作为 Vue <template> 中的标签访问,我通常只会在其中编写<div>{{ myReactiveData }}</div>

<template>
    <div ref="myDiv"></div>
</template>

<script>
    import { defineComponent, ref } from 'vue';
    
    export default defineComponent({    
        
        setup()
        {
            // Lets pretend this is some kind of third party vanilla JS component, not originally made for Vue
            const someComponent = document.createElement('div');
            const nestedDiv = document.createElement('div');
            someComponent.appendChild(nestedDiv);
            
            // Setup some normal Vue stuff, 'myDiv' is the root div ref
            const myDiv = ref(null)
            
            onMounted( () => {
                // Add the "Third party element" to the DOM
                myDiv.value.appendChild(someComponent);
            });
            
            // What I want to do, is to add a reactive property nested inside the vanilla js component
            const myReactiveData = ref('Initial string');
            nestedDiv.innerText = myReactiveData.value; // This doesn't work, it is not reactive at runtime
            
            setTimeout(()=>{
                myReactiveData.value = 'Hello world!'; // Never updates
            }, 1000);

            return { myDiv, myReactiveData };
        
        },
    });
</script>

这是watchwatchEffect的用例。 基本上,您要做的是在某些反应性数据更改时执行副作用(强制更新您的 DOM)。 您可以参考官方文档了解如何使用它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM