Vue 中使用Pug

时间:2022-07-23
本文章向大家介绍Vue 中使用Pug,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原文地址 https://www.aiprose.com/blog/126

1 介绍 pug 是一种前端模板引擎,原名 jade

可用来生成 HTML,它的写法类似于 CSS

这里先简单举几个例子

#hello
<div id="hello"></div>
a.link-button Link
<a class="link-button">Link</a>

易理解,同时极大的简约了我们的代码。

2 安装 2.1 下载

npm i -D pug pug-html-loader pug-plain-loader
或者
yarn add pug pug-html-loader pug-plain-loader

2.2 配置 // vue.config.js

module.exports = {
    chainWebpack: config => {
      config.module.rule('pug')
        .test(/.pug$/)
        .use('pug-html-loader')
        .loader('pug-html-loader')
        .end()
  }
}

2.3 使用,注意要加 lang=“pug”

<template lang="pug">
    div.hello
        h1 Hello World
</template>

3 实践 下面将拿出实际项目中的一些代码进行改造

原代码

<template>
    <div class="gallery">
        <div class="btn-group">
            <span>选择相册:</span>
            <Select v-model="cataId" style="width:200px">
                <Option v-for="item in catalogs" :value="item.id" :key="item.id" clearable>{{ item.name }}</Option>
            </Select>
            <Button type="info">上传照片</Button>
        </div>
        <vue-waterfall-easy :imgsArr="imgsArr" @scrollReachBottom="loadMore" ref="waterfall"></vue-waterfall-easy>
    </div>
</template>

改造后 12行代码变成9行,标签完全简化

<template lang="pug">
    .gallery
        .btn-group
            span 选择相册:
            Select(v-model="cataId" style="width:200px")
                Option(v-for="item in catalogs" :value="item.id" :key="item.id" clearable) {{ item.name }}
            Button(type="info") 上传照片
        vue-waterfall-easy(:imgsArr="imgsArr" @scrollReachBottom="loadMore" ref="waterfall")
</template>