You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js如何格式化WordPress REST API返回的HTML响应内容

Vue.js如何格式化WordPress REST API返回的HTML响应内容

嘿,我明白你的问题啦——你现在通过Vue调用WordPress REST API获取单篇文章后,页面上直接显示了带HTML标签的文本,而不是渲染好的富内容对吧?这是因为Vue默认的双大括号插值会自动转义HTML内容,所以标签会被当成普通文本显示出来。

别担心,解决方法很简单,你只需要把文本插值换成v-html指令就可以了,它会帮你把HTML内容正确渲染到页面上。

修改后的Vue代码(仅需调整template部分)

<template>
  <div>
    <h1>Single Post Page</h1>
    <div v-if="postLoaded" v-html="post.content.rendered"></div>
    <p v-else>Please wait ...</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postLoaded : false,
      post : null,
    }
  },
  mounted() {
    let postId = this.$route.params.id;
    axios.get('https://amarcourse.com/wp-json/wp/v2/posts/' + postId )
    .then((response) => {
      this.post = response.data;
      this.postLoaded = true;
    })
    .catch((error) => {
      console.log(error)
    })
    .finally(() => {});
  }
}
</script>

<style>
</style>

简单解释下原理:

  • 原来的{{ post.content.rendered }}是文本插值,Vue会把所有HTML标签转义成普通字符(这是默认的安全机制),但这也导致你的文章格式无法正常显示。
  • v-html指令的作用是直接更新元素的innerHTML,它会把传入的HTML字符串解析并渲染成对应的DOM元素,正好匹配你需要显示WordPress富文本内容的需求。

⚠️ 小提醒:如果你的网站允许用户提交自定义HTML内容,使用v-html要注意XSS安全问题哦!不过这里是从你自己的WordPress后台获取的文章内容,只要后台内容是安全的,就不用担心这个问题。

备注:内容来源于stack exchange,提问作者Shibbir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 11:17:47