英文:
How to access server rendered HTML in Vue JS component?
问题
在Vue JS组件中获取服务器渲染的HTML有没有办法?
我有一个名为MathComponent
的组件,它使用数学公式在屏幕上显示文本。但我不希望它像其他组件一样进行水合处理。相反,我想显示服务器生成的输出,而不是重新生成它。 这样,我可以防止在客户端执行该数学公式。
我真的很想这样做。所以请不要浪费我的时间说“执行数学公式对网站性能影响不大”或类似的话。
谢谢
英文:
Is there any way to get server rendered HTML in Vue JS component?
I have a component called MathComponent
that displays a text on the screen using mathematical formula. But I don't want it to hydrate like other components. Rather, I want to display the output generated by the server instead of regenerating it. In this way, I can prevent the execution of that mathematical formula in client side.
I really want to do this. So please don't take my time by saying "executing a mathematical formula doesn't have much effect on website performance" or anything similar.
Thank you
答案1
得分: 2
以下是翻译好的内容:
如果您想从服务器呈现常规的HTML,请使用fetch
从后端获取它,然后使用v-html
和v-if
/v-else
进行显示:
<script setup>
import { ref } from 'vue';
const html = ref('');
async function loadHtml() {
html.value = await fetch('/your-url').then(r => r.text())
}
</script>
<template>
<button @click="loadHtml">加载HTML</button>
<div v-if="html" v-html="html"></div>
<div v-else>
直到从后端更新之前,请在此处放置您的组件。
</div>
</template>
英文:
If you want to render a usual HTML from the server, use fetch
to fetch it from the backend, and display with v-html
and v-if
/v-else
:
<script setup>
import { ref } from 'vue';
const html = ref('');
async function loadHtml() {
html.value = await fetch('/your-url').then(r => r.text())
}
</script>
<template>
<button @click="loadHtml">Load html</button>
<div v-if="html" v-html="html"></div>
<div v-else>
Your component here until you update from the backend.
</div>
</template>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论