双大括号会将数据解释为普通文本,而非 HTML 代码。为了输出真正的 HTML,你需要使用 v-html 指令:
<p>Using mustaches: {{ rawHtml }}</p>

<p>Using v-html directive: <span v-html="rawHtml"></span></p>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="vue.js"></script>
    </head>
    <body>
        <div id="app">Message: {{ msg }}</div>
        <script type="text/javascript">
            var vm = new Vue({
                    el: "#app",
                    data:{
                        msg: "Hello Vue!",
                    }
                });
                vm.msg = "Hello New Vue Info!";
        </script>
        <div id="app-1" v-once>Message: {{ Message }}</div>
        <script type="text/javascript">
            var app10 = new Vue({
                    el: "#app-1",
                    data:{
                        Message: "Hello Vue!",
                    }
                });
                app10.Message = "Hello New Vue Infos!";
        </script>
        <div id="app-2" v-once>
            Html: {{ Message }}
            <p>Using mustaches: {{ Html }}</p>      
            <p v-html="Html">{{ Html }}</p>
        </div>
        <script type="text/javascript">
            var app2 = new Vue({
                    el: "#app-2",
                    data:{
                        Message : "Hello Vue!",
                        Html : '<span style="color:red;">this is should be read Html!</span>',
                    }
                });
        </script>     
    </body>
</html>

v-html 指令

Message: Hello New Vue Info!
Message: Hello Vue!
Html: Hello Vue!
Using mustaches: <span style="color:red;">this is should be read Html!</span>
this is should be read Html!

这个 span 的内容将会被替换成为属性值 rawHtml,直接作为 HTML——会忽略解析属性值中的数据绑定。注意,你不能使用 v-html 来复合局部模板,因为 Vue 不是基于字符串的模板引擎。反之,对于用户界面 (UI),组件更适合作为可重用和可组合的基本单位。
你的站点上动态渲染的任意 HTML 可能会非常危险,因为它很容易导致 XSS 攻击。请只对可信内容使用 HTML 插值,绝不要对用户提供的内容使用插值。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部