【109】行内元素间的换行符导致出现空隙。Vue用删除标签间换行符解决。

场景重现

读者可以到 这里写链接内容
去阅读整个演示项目的源代码。本文只给出关键代码。

文件结构

blog109
  │
  ├─.babelrc
  ├─.npmrc
  ├─index.template.html
  ├─package.json
  ├─webpack.config.js
  ├─yarn.lock
  └─src
     │
     ├─App.vue
     ├─home.vue
     ├─main.js
     └─router.js

webpack.config.js

var path = require('path')
var webpack = require('webpack')
const HTMLPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
        app: ['./src/main.js'],
        // 把共用的库放到vendor.js里
        vendor: [
            'babel-polyfill',
            'vue',
            'vue-router'
        ]
    },
  output: {
    path: path.resolve(__dirname, './dist'),

    // 因为用到了 html-webpack-plugin 处理HTML文件。处理后的HTML文件都放到了
    // dist文件夹里。html文件里面js的相对路径应该从使用 html-webpack-plugin 前
    // 的'/dist/' 改成 '/'
    publicPath: '/',
    // publicPath: '/dist/',
    filename: '[name].[hash].js'
    // filename:'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here

        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      // font loader
      {
        test: /\.(ttf|eot|woff|svg)$/i,
        loader: 'url-loader'
      },
      // 图片处理
      {
        test: /\.(png|jpg|gif)$/,
        loader: 'url-loader',
        options: {
          limit: '1000',
          name: '[name].[ext]?[hash]'
        }
      },
      {
        test: /\.(docx)$/,
        loader: 'url-loader',
        options: {
          limit: '10',
          name: '[name].[ext]'
        }
      }
      // {
      //   test: /\.(png|jpg|gif|svg)$/,
      //   loader: 'file-loader',
      //   options: {
      //     name: '[name].[ext]?[hash]'
      //   }
      // }
    ]
  },
  plugins:[
    // 把共用的库放到vendor.js里
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
    // 编译HTML。目的:在生产环境下,为了避免浏览器缓存,需要文件按照哈希值重命名。
    // 这里编译可以自动更改每次编译后引用的js名称。
    new HTMLPlugin({template: 'index.template.html'})
  ],
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

home.vue

<template>
    <div>
        <a class="blog109-a">文字1</a>
        <a class="blog109-a">文字2</a>
        <a class="blog109-a">文字3</a>
        <a class="blog109-a">文字4</a>
    </div>
</template>
<script>
    export default {
        data(){

            return {

            };
        }
    };
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
    .blog109-a{
        color: white;
        background-color: red;
        padding: 0;
        margin: 0;
        border: 0;
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: transparent;
        cursor: pointer;
    }
</style>

效果如图:

1.png

产生这个问题的原因在于,a 标签间的空格和换行符被解析成文本节点,产生了空隙。当然,在源代码中删除 a 标签间的空格和换行是可以解决此问题。但是代码格式难以阅读。

解决办法

既要保证代码可以阅读,又要保证效果,可以考虑在编译选项上着手。vue-loader提供了这样的选项来方便开发者。修改方法非常简单,只要在 webpack.config.js配置文件中,对vue-loader加入preserveWhitespace: false 就可以了。

修改后的 webpack.config.js 文件内容如下:

var path = require('path')
var webpack = require('webpack')
const HTMLPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
        app: ['./src/main.js'],
        // 把共用的库放到vendor.js里
        vendor: [
            'babel-polyfill',
            'vue',
            'vue-router'
        ]
    },
  output: {
    path: path.resolve(__dirname, './dist'),

    // 因为用到了 html-webpack-plugin 处理HTML文件。处理后的HTML文件都放到了
    // dist文件夹里。html文件里面js的相对路径应该从使用 html-webpack-plugin 前
    //'/dist/' 改成 '/'
    publicPath: '/',
    // publicPath: '/dist/',
    filename: '[name].[hash].js'
    // filename:'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
          ,preserveWhitespace: false // 默认值是true,如果设置为 false,模版中 HTML 标签之间的空格将会被忽略。
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      // font loader
      {
        test: /\.(ttf|eot|woff|svg)$/i,
        loader: 'url-loader'
      },
      // 图片处理
      {
        test: /\.(png|jpg|gif)$/,
        loader: 'url-loader',
        options: {
          limit: '1000',
          name: '[name].[ext]?[hash]'
        }
      },
      {
        test: /\.(docx)$/,
        loader: 'url-loader',
        options: {
          limit: '10',
          name: '[name].[ext]'
        }
      }
      // {
      //   test: /\.(png|jpg|gif|svg)$/,
      //   loader: 'file-loader',
      //   options: {
      //     name: '[name].[ext]?[hash]'
      //   }
      // }
    ]
  },
  plugins:[
    // 把共用的库放到vendor.js里
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
    // 编译HTML。目的:在生产环境下,为了避免浏览器缓存,需要文件按照哈希值重命名。
    // 这里编译可以自动更改每次编译后引用的js名称。
    new HTMLPlugin({template: 'index.template.html'})
  ],
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

间隙全部消除后的效果:

2.png

注意

虽然 preserveWhitespace: false 可以删除标签间的空格,但是v-html 配合样式 white-space:pre-wrap 还是可以保留DIV 标签中的空格和换行的。

加了v-html后的home.vue 如下:

<template>
    <div class="blog109-div">
        <a class="blog109-a">文字1</a>
        <a class="blog109-a">文字2</a>
        <a class="blog109-a">文字3</a>
        <a class="blog109-a">文字4</a>
        <div v-html="myHtml" class="blog109-myHtml"></div>
    </div>
</template>
<script>


    export default {
        data(){

            return {
                myHtml: "    sljdldfj\nlsjdflkj"
            };
        }
    };
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
    .blog109-div{
        text-align: center;
    }
    .blog109-a{
        color: white;
        background-color: red;
        padding: 0;
        margin: 0;
        border: 0;
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: transparent;
        cursor: pointer;
    }
    .blog109-myHtml{
        white-space:pre-wrap
    }
</style>

v-html 中的空格和回车依然保留:

3.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值