技术博客

越是喧闹,越是孤独。越是寂寞,越是丰富
The more noisy, the more lonely. The more lonely, the more rich

越是喧闹,越是孤独。越是寂寞,越是丰富
The more noisy, the more lonely. The more lonely, the more rich

技术博客


升级Vue3.0后对空格的处理

2022-09-24 Mendel
Vue


本文是对之前的文章《本站已升级到Vue3.x》的一个补充,供大家参考。




01

问题发现



升级到Vue3后,突然发现底部footer区域的三个超链接文字无间距的挨在一起了,如下图:


而升级前是正常的情况:


于是看了下这部分的HTML代码,试图寻找一些原因:

<div class="small text-muted">    Powered By    <a class="text-muted" href=" " target="_blank">Bootstrap</ a>    <a class="text-muted" href="https://cn.vuejs.org/" target="_blank">Vue.js</ a>    <a class="text-muted" href="https://webpack.js.org/" target="_blank">Webpack</ a>    <br>    Copyright &copy; 2021-2022 mengchen.cc. All rights reserved. <br>    <a class="text-muted" href="https://beian.miit.gov.cn" target="_blank">京ICP备2021011285号-1</ a></div>


这里是连续的三个<a>标签,一个占一行。当内联元素之间有连续的空格或换行符时,在显示效果上看都是一个空格的间距。于是猜想,可能是Vue抹掉了这些空白内容。于是查阅了下文档发现确实如此。




02


问题解决


Vue 3.x 官方文档中有如下这么一个配置项:

(https://cn.vuejs.org/api/application.html#app-config-compileroptions-whitespace)


于是按照文档上建议的方式进行配置

app.config.compilerOptions.whitespace = 'preserve'

然而,It doesn't work. 接着又看到了这一段描述:



因为本站采用的是 webpack 构建的Vue项目,所以需要用另外的方式,但是根据这里的参考链接,尝试了几种方式均不奏效。


最后,终于在Stackoverflow上找到了一个办法成功解决了我的问题:

(https://stackoverflow.com/questions/69055857/preserve-whitespace-between-spans-in-vue


按照该answer所述,修改我的webpack.config.js的配置之后,空格问题就正常解决了

rules: [  {    test: /\.vue$/,    loader: 'vue-loader',    options: {      compilerOptions: {        whitespace: 'preserve'      }    }  }]




03


总结


Vue3既然默认行为就是去除空白字符,那么一定是有他的考虑。就像文档中所述,是为了更高效的模板输出,提升模板编译效率。于是查阅了相关资料,其中一篇详细描述了Vue对空白字符的优化,这里分享给大家:


Vue3 编译之美,原来空白字符也能优化?
https://zhuanlan.zhihu.com/p/550357781






相关文章