[英]How to add reactive data to nested vanilla DOM elements in Vue 3?
How can I add reactive data to DOM elements in the runtime?如何在运行时向 DOM 元素添加响应式数据? I do not have access to these elements as tags in the Vue <template>, where I would normally just write <div>{{ myReactiveData }}</div> .我无法将这些元素作为 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>
This is the use case of watch
or watchEffect
.这是watch
或watchEffect
的用例。 Basically what you are trying to do is to perform a side effect (imperatively updating your DOM) when some reactive data changes.基本上,您要做的是在某些反应性数据更改时执行副作用(强制更新您的 DOM)。 You can refer to the official documentation for how those should be used您可以参考官方文档了解如何使用它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.