1. 选项式 Options API
<script>
export default {
data() {
return {
}
},
methods: {
},
mounted() {
}
}
</script>
2. 组合式 Composition API;按需导入,并采用 setup 语法糖 - 推荐使用
<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
</script>
1. 创建
创建组件/子组件,后缀名为 .vue,如 HelloWorld.vue
可以根据需要定制模板 - 调整三个部分的前后顺序;如把 <script> 调整到前面
不使用 CSS 预处理
<script setup>
</script>
<template>
<h1>Hello World</h1>
</template>
<style scoped>
</style>
2. 引入
父组件在 <script> 引入子组件
引入时,输入组件部分或全名,IDE会自动获取组件及补充相对路径;注意看代码提示
不能省略后缀名 .vue
可以使用相对路径
也可以使用路径别名 @ 从 src 开始引用
<script setup>
import HelloWorld from '@/components/HelloWorld.vue'
</script>
为了按需引入,减少加载时间,特别是首屏加载,通常采用
异步组件
的形式引入
采用了异步组件,打包的时,会拆分成多个 .js 文件
import { defineAsyncComponent } from 'vue'
const HelloWorld = defineAsyncComponent(() =>
import('./components/HelloWorld.vue')
)
3. 使用
父组件在结构 <template> 中使用组件/子组件
怎么引入就怎么使用;可以使用单标签或双标签
可以多次使用
使用 PascalCase 格式以保持一致性,有助于区分原生元素
<template>
<h1>Here is a child component!</h1>
<HelloWorld />
<HelloWorld></HelloWorld>
</template>