Vue v-html用法
如果我们从服务器端获取到了HTML字符串,用浏览器显示出来。在Vue框架下,可以用v-html指令来做。例如:<!DOCTYPE html><html><head><meta charset="utf-8"><title>vue demo</title></head><body><script s
·
如果我们从服务器端获取到了HTML字符串,用浏览器显示出来。在Vue框架下,可以用v-html指令来做。例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue demo</title>
</head>
<body>
<script src="./vue.js"></script>
<div id="app">
<div v-html="hello"></div>
</div>
<script>
const app = new Vue({
el: '#app',
data: function () {
return {
hello: "<html>\n" +
"<head>\n" +
" <style type=\"text/css\">\n" +
" #app{\n" +
" width: 600px;\n" +
" height: 600px;\n" +
" background-color: green;\n" +
" margin: auto;\n" +
" color: red;\n" +
" text-align: center;\n" +
" font-size: 60px;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"<body>\n" +
"<div id=\"app\">hello world</div>\n" +
"</body>\n" +
"</html>\n"
}
},
})
</script>
</body>
</html>
模板编译后的匿名函数为:
function anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('div',{domProps:{"innerHTML":_s(hello)}})])}
}
从匿名函数中可以看出,v-html指令解析成了innerHTML。所以在节点元素上直接用innerHTML也是可以的,例如:
<html>
<head>
</head>
<body>
<div id="app"></div>
<script>
document.getElementById('app').innerHTML = "<html>\n" +
"<head>\n" +
" <style type=\"text/css\">\n" +
" #app{\n" +
" width: 600px;\n" +
" height: 600px;\n" +
" background-color: green;\n" +
" margin: auto;\n" +
" color: red;\n" +
" text-align: center;\n" +
" font-size: 60px;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"<body>\n" +
"<div id=\"app\">hello world</div>\n" +
"</body>\n" +
"</html>\n"
</script>
</body>
</html>
更多推荐
所有评论(0)