Vue
Vue.js 是一个渐进式、可增量采用的 JavaScript 框架,用于构建 Web 上的 UI。Parcel 使用 @parcel/transformer-vue
插件自动支持 Vue。当检测到 .vue
文件时,它将自动安装到您的项目中。
注意:Parcel 不支持使用 Vue 2 的 SFC,您必须使用 Vue 3 或更高版本。
示例用法
#index.html
<!DOCTYPE html>
<div id="app"></div>
<script type="module" src="./index.js"></script>
index.js
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
app.mount("#app");
App.vue
<template>
<div>Hello {{ name }}!</div>
</template>
<script>
export default {
data() {
return {
name: "Vue",
};
},
};
</script>
HMR
#Parcel 使用官方的 Vue SFC 编译器,它开箱即用地支持 HMR,因此您将获得快速、响应式的开发体验。有关 Parcel 中 HMR 的更多详细信息,请参阅 热重载。
Vue 3 特性
#由于 Parcel 使用 Vue 3,因此您可以使用所有 Vue 3 特性,例如 组合 API。
App.vue
<template>
<button @click="increment">
Count is: {{ state.count }} Double is: {{
state.double }}
</button>
</template>
<script>
import { reactive, computed } from "vue";
export default {
setup() {
const state = reactive({
count: 0,
double: computed(() => state.count * 2),
});
function increment() {
state.count++;
}
return {
state,
increment,
};
},
};
</script>
语言支持
#Parcel 支持 JavaScript、TypeScript 和 CoffeeScript 作为 Vue 中的脚本语言。
几乎可以使用任何模板语言(所有由 consolidate 支持的语言)。
对于样式,支持 Less、Sass 和 Stylus。此外,可以使用 module
和 scoped
修饰符与 CSS 模块 和 作用域样式。
App.vue
<style lang="scss" scoped>
/* This style will only apply to this module */
$red: red;
h1 {
background: $red;
}
</style>
<style lang="less">
@green: green;
h1 {
color: @green;
}
</style>
<style src="./App.module.css">
/* The content of blocks with a `src` attribute is ignored and replaced with
the content of `src`. */
</style>
<template lang="pug"> div h1 This is the app </template>
<script lang="coffee">
module.exports =
data: ->
msg: 'Hello from coffee!'
</script>
自定义块
#您可以在 Vue 组件中使用自定义块,但必须使用 .vuerc
、vue.config.js
等配置 Vue 来定义如何预处理这些块。
.vuerc
{
"customBlocks": {
"docs": "./src/docs-preprocessor.js"
}
}
src/docs-preprocessor.js
export default function (component, blockContent, blockAttrs) {
if (blockAttrs.brief) {
component.__briefDocs = blockContent;
} else {
component.__docs = blockContent;
}
}
HomePage.vue
<template>
<div>Home Page</div>
</template>
<docs> This component represents the home page of the application. </docs>
<docs brief> Home Page </docs>
App.vue
<template>
<div>
<child></child>
docs: {{ docs.standard }} in brief: {{
docs.brief }}
</div>
</template>
<script>
import Child from "./HomePage.vue";
export default {
components: {
child: Child,
},
data() {
let docs = { standard: Child.__docs, brief: Child.__briefDocs };
return { docs };
},
};
</script>