VueJ에서 부모 요소가 없는 요소만 렌더링하려면 어떻게 해야 합니까?
코드:
<div :v-html="html"></div>
현재 출력
<div><image/></div>
예상되는 출력
<image />
질문에 대한 답변
다음과 같은 커스텀 컴포넌트를 작성할 수 있습니다.
vue2의 경우:
Vue 앱을 초기화하기 전에 플러그인을 추가합니다. 그러면 html 문자열이 단일 html 루트로 래핑되었는지 확인합니다.
String.prototype.hasHtmlCloak = function() {
return /<(br basefont hr input source frame param area meta !-- col link option base img wbr !DOCTYPE).*?> <(a abbr acronym address applet article aside audio b bdi bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dialog dir div dl dt em embed fieldset figcaption figure font footer form frameset head header hgroup h1 h2 h3 h4 h5 h6 html i iframe ins kbd keygen label legend li map mark menu meter nav noframes noscript object ol optgroup output p pre progress q rp rt ruby s samp script section select small span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr track tt u ul var video).*?</2>$/i.test(this); }
예를 들어 다음과 같습니다.
'<div><image/></div>'.hasHtmlCloak(); // true '<image/>'.hasHtmlCloak(); // false '<div><image/>'.hasHtmlCloak(); // false
SmartCloak.js
export default {
props: {
templateString: {
required: true
},
cloak: {
required: false,
default: 'div'
}
},
computed: {
withCloak() {
let inner = this.templateString
"";
return inner.toString().hasHtmlCloak() ?
inner :
`<${this.cloak}>${inner}</${this.cloak}>`;
}
},
render(h) {
let self = this;
return h({
template: self.withCloak
});
} }
빌드 도구에 구성을 추가해야 할 수도 있습니다.자세한 내용은 문서를 참조하십시오: Runtime + Compiler vs. 런타임 전용
// if you are using webpack
build: {
extend(config, ctx){
config.resolve.alias['vue'] = 'vue/dist/vue.common';
}
},
// if you are using vite
vite: {
resolve: {
alias: {
'vue': 'vue/dist/vue.common'
}
},
}
그 후, 이 기능을 사용하여.vue
아래와 같이 파일하다
<template>
<SmartCloak
:template-string="myHtmlString"/> // use it like v-html </template>
<script> import SmartCloak from '~/components/SmartCloak.js';
export default {
components: {
SmartCloak
},
data() {
return {
myHtmlString: `<img src="http://example.com/1.jpg"/>`,
}
} } </script>