Vue
Vue.js 是一个渐进式、可逐步采用的 JavaScript 框架,用于在 Web 上构建用户界面。Parcel 通过 @parcel/transformer-vue
插件自动支持 Vue。当检测到 .vue
文件时,它将自动安装到您的项目中。
note: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>你好 {{ 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">
计数是:{{ state.count }} 双倍是:{{
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 支持在 Vue 中使用 JavaScript、TypeScript 和 CoffeeScript 作为脚本语言。
几乎可以使用任何模板语言(consolidate 支持的所有语言)。
对于样式,支持 Less、Sass 和 Stylus。此外,可以使用 module
和 scoped
修饰符来使用 CSS 模块和作用域样式。
App.vue:
<style lang="scss" scoped>
/* 这个样式只会应用到这个模块 */
$red: red;
h1 {
background: $red;
}
</style>
<style lang="less">
@green: green;
h1 {
color: @green;
}
</style>
<style src="./App.module.css">
/* 带有 `src` 属性的块的内容会被忽略,并替换为 `src` 的内容。 */
</style>
<template lang="pug"> div h1 这是应用 </template>
<script lang="coffee">
module.exports =
data: ->
msg: '来自 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>主页</div>
</template>
<docs> 这个组件代表应用的主页。 </docs>
<docs brief> 主页 </docs>
App.vue:
<template>
<div>
<child></child>
文档:{{ docs.standard }} 简要:{{ 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>