我正在構建一個 WYSIWYG 型別的應用程式,其中用戶可以在 textarea 中撰寫 CSS,并且該 CSS 規則將應用于頁面上的 HTML 我在模板中嘗試了類似的操作
<textarea v-bind="css"></textarea>
<style v-html="css"></style>
VueCompilerError:在客戶端組件模板中忽略具有副作用 ( 和 ) 的標簽。
uj5u.com熱心網友回復:
舊答案,下面是更好的答案
使用 v-model 添加 textarea:
<textarea v-model="css" />您可以在 onMounted 鉤子中創建樣式標簽:
onMounted(() => { const style = document.createElement("style"); style.type = "text/css"; updateCss(style, css.value); document.getElementsByTagName("head")[0].appendChild(style); el.value = style; });您必須能夠稍后訪問此元素,因此將樣式分配給 el.value。
然后在輸入值上添加監視:
watch(css, () => { updateCss(el.value, css.value); });其中 updateCss 是一個函式:
const updateCss = (el, css) => { if (el.styleSheet) { el.styleSheet.cssText = css.value; } else { el.innerHTML = ""; el.appendChild(document.createTextNode(css)); } };演示:
https://codesandbox.io/s/cocky-mestorf-uqz6f?file=/src/App.vue:246-463
編輯
我找到了更好的解決方案:
<template>
<textarea v-model="css" />
<component :is="'style'" type="text/css" v-text="css"></component>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const css = ref("body { background-color: blue; }");
return { css };
},
};
</script>
組件不會拋出關于樣式標簽的錯誤:
<component :is="'style'">
請注意,有 v-text 而不是 v-html。V-html 可能不安全。
演示:https : //codesandbox.io/s/festive-germain-q9tg3?file=/src/ App.vue: 122-281
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352350.html
標籤:javascript css Vue.js 所见即所得
上一篇:如何停止執行直到函式完成
