如何在Vue JS组件中访问服务器渲染的HTML?

huangapple go评论59阅读模式
英文:

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-htmlv-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>

huangapple
  • 本文由 发表于 2023年7月18日 15:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定