使用WebStorm开发Vue 3项目过程中,在新建vue组件时,ws内置的模板还是vue2.0时代JS版本的,但是ws允许自定义组件模板,模板语言是基于Java的解析器VeloCity,可以自定义变量,使用简单的Java字符串处理方法等等;
ws的template中默认提供了许多变量,可以获取组件名称,当前路径时间等;
## webstorm默认的Vue模板
<template>
#[[$END$]]# <!--文件建立完成后光标停留位置-->
</template>
<script>
export default {
name: "${COMPONENT_NAME}" // ${...}自定义变量
}
</script>
<style scoped>
</style>
默认组件长这样,而我需要创建的Vue 3 + vue classs component 典型组件
DemoView.vue
<template>
<!--div class 通过将类名的大驼峰命名转换为蛇形命名法获取-->
<div class="demo-view">
</div>
</template>
<script lang="ts">
import {Options, Vue} from "vue-class-component";
@Options({})
export default class DemoView extends Vue {
// 类名通过${FILE_NAME}截取文件扩展名之后获得
}
</script>
<style lang="scss" scoped>
</style>
根据此写出的模板如下
#set( $LAST_INDEX = $FILE_NAME.length() - 4 )
#set( $COMPONENT_NAME = $FILE_NAME.substring(0,$LAST_INDEX ) )
#set( $SNAKECASE_NAME = $COMPONENT_NAME.substring(0,1).toLowerCase() + $COMPONENT_NAME.substring(1).replaceAll("([A-Z])", "-$1").toLowerCase() )
<template>
<div class="${SNAKECASE_NAME}">
#[[$END$]]#
</div>
</template>
<script lang="ts">
import {Options, Vue} from "vue-class-component";
@Options({})
export default class ${COMPONENT_NAME} extends Vue{
}
</script>
<style lang="scss" scoped>
</style>
首先我们定义了COMPONENT_NAME对COMPONENT_NAME转换为为蛇形命名法,先将$COMPONENT_NAME首字母提取转换为小写字母,然后将剩余部分中的大写字母转换位小写,并在转换位置前添加 - ,这样在新建时只需输入文件名,组件就建立好了。