从数据库读取一个字符串,例如: 这种形式.将这个字符串保存到一个常量.
需要将这个字符串显式成标签.
内容大概是下面这个样子:
<script setup>
const temp = "<icon-home />";
</script>
<template>
<span v-html="temp "></span>
<span>{{temp }}</span>
</template>
都不能正常显示这个标签,请问有什么办法能将字符串(字符串是标签格式)显示成标签了?
楼主可以看看我的方案 如果可以 点个采纳 多谢 。要将一个字符串作为标签来显示,可以使用 Vue 的动态组件或 v-html
指令。下面是使用这两种方式的示例:
component
元素包裹,将动态组件名称绑定到 is
属性上。<template>
<component :is="temp"></component>
</template>
v-html
指令:v-html
指令上。v-html
指令会将字符串作为 HTML 解析,并将其渲染为对应的标签。<template>
<span v-html="temp"></span>
</template>
请注意,在使用 v-html
指令时,要确保字符串内容来自可信任的来源,并且没有包含恶意代码,以防止安全风险。
另外,请注意,在 Vue 3 中,使用 <script setup>
语法时,暂时无法直接访问组件中的数据和方法。因此,你可以将 const temp = "<icon-home />";
移动到 setup()
函数中,并通过返回值的方式将其暴露给模板使用。
<script setup>
import { ref } from 'vue';
const temp = ref("<icon-home />");
export default {
setup() {
return {
temp
};
}
};
</script>
<template>
<component :is="temp"></component>
<span v-html="temp"></span>
</template>
通过这种方式,你可以在 Vue 组件中将字符串作为标签格式正确地显示出来。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>天知道</title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<div class="wrap" id="app">
<div class="search_form">
<div class="logo"><img src="img/logo.png" alt="logo" /></div>
<div class="form_group">
<input type="text" v-model="city" @keyup.enter="searchWeather"
class="input_txt" placeholder="请输入查询的天气"/>
<button class="input_sub" @click="searchWeather">
搜 索
</button>
</div>
<div class="hotkey">
<a href="javascript:;" @click="changeCity('北京')">北京</a>
<a href="javascript:;" @click="changeCity('上海')">上海</a>
<a href="javascript:;" @click="changeCity('广州')">广州</a>
<a href="javascript:;" @click="changeCity('深圳')">深圳</a>
</div>
</div>
<ul class="weather_list">
<li v-for="item in weatherList">
<div class="info_type"><span class="iconfont">{{ item.type }}</span></div>
<div class="info_temp">
<b>{{ item.low }}</b>
~
<b>{{ item.high }}</b>
</div>
<div class="info_date"><span>{{ item.date }}</span></div>
</li>
</ul>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 自己的js -->
<script src="./js/main.js"></script>
</body>
</html>