Pug 是一種高效的、簡潔的模板引擎,它使用縮進、可選的括號和強制縮寫等語法規則來簡化 HTML/CSS/JS 的書寫。Pug 簡化了模板的書寫,可以通過縮進來表示嵌套關係,使用小括號包裹指令和屬性,並且使用換行符來分隔標籤,使得代碼層次更加清晰有序。
舉個例子,以下是一個常見的 HTML 表單:
```html
<form action="/submit" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<button type="submit">Submit</button>
</form>
```
而使用 Pug 來書寫同樣的表單,可以寫成:
```pug
form(action="/submit", method="post")
label(for="username") Username:
input(type="text", id="username", name="username")
label(for="password") Password:
input(type="password", id="password", name="password")
button(type="submit") Submit
```
可以看到,Pug 將 HTML 中的標籤、屬性、內容等分拆開來,用縮進來表示嵌套關係,並用小括號將屬性和指令包裹,以便於閱讀和維護。
在 Vue 中使用 Pug 模板引擎,需要先安裝依賴:
```
npm install -D pug pug-plain-loader
```
安裝完成後,在 Vue 的單文件組件中,可以使用 `<template lang="pug">` 定義 Pug 模板。例如:
```vue
<template lang="pug">
div
p Hello, {{ name }}!
</template>
<script>
export default {
data() {
return {
name: 'world',
};
},
};
</script>
```
其中,`<template lang="pug">` 中的 Pug 代碼將被編譯爲渲染函數,並在組件實例的 `render()` 方法中使用。
如果使用 Webpack 構建工具,可以在 `webpack.config.js` 文件中配置 Pug:
```js
module.exports = {
// ...
module: {
rules: [
{
test: /\.pug$/,
loader: 'pug-plain-loader',
},
],
},
};
```
這樣就可以在 Vue 單文件組件中使用 Pug 模板引擎了。在使用時,需要注意縮進和換行符的使用,確保代碼正確編譯和渲染。同時,Pug 支持內置的 Vue 語法和指令,可以使用 `v-` 前綴來表示,例如 `v-if`、`v-for` 等。