为什么Vue忽略css规则?



我有以下html代码

<head>
<script src="https://unpkg.com/vue@3"></script>
<script defer src="script.js"></script>
</head>
<body>
<div id="main">        
<div>
1. This is 1st line
2. This is 2nd line
3. This is 3rd line
</div>
<br>
<div style="white-space: pre-line;">
1. This is 1st line
2. This is 2nd line
3. This is 3rd line
</div>
</div>
</body>

这将导致

1. This is 1st line 2. This is 2nd line 3. This is 3rd line

1. This is 1st line
2. This is 2nd line
3. This is 3rd line

但是,当我将一个Vue实例挂载到主div上时,我得到的结果是

1. This is 1st line 2. This is 2nd line 3. This is 3rd line
1. This is 1st line 2. This is 2nd line 3. This is 3rd line

script.js文件中Vue实例的代码如下

const test = Vue.createApp({
}).mount("#main")

为什么我的空白样式被完全忽略了?

Vue编译器默认折叠空白,因此原始代码中的换行符被折叠(删除多余的空白),以产生更有效的编译输出。

选项1:应用配置禁用whitspace - condensed

您可以全局禁用在您的示例中,将app.config.compilerOptions.whitespace设置为'preserve':

const app = Vue.createApp({})
app.config.compilerOptions.whitespace = 'preserve'
app.mount("#main")

演示1

或者每个组件禁用它:

const app = Vue.createApp({
compilerOptions: {
whitespace: 'preserve'
}
})
app.mount("#main")

演示2

注意:app.config.compilerOptions.whitespace仅在使用完整构建时受到尊重。否则,您必须通过构建标志来设置该选项。

选项2:构建标志禁用whitspace - condensed

您可以配置@vue/compiler-sfc禁用此Vite配置中的空白压缩:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
whitespace: 'preserve', 👈
},
},
}),
],
})

演示3

选项3:在需要换行的地方使用<br>

或者,您可以显式地在需要的地方添加<br>标记,这将在实现所需间距的同时保持最初预期的优化:

<div>
1. This is 1st line<br>
2. This is 2nd line<br>
3. This is 3rd line<br>
</div>

最新更新