1. 定义组件
<template>
<div>{{count}}</div>
<br >
<button @click="addcount">count++</button>
</template>
<script setup>
//注意上方使用script标签内书写了setup 这个单文件组件是私有的
//此组件的父控件不会访问到此组件任何的属性
//如果想访问请使用defineExpose宏显示暴漏
//defineExpose({属性名称,方法名称})
import {ref} from 'vue'
let count=ref(1)
function addcount(){
count.value++
}
</script>
<style>
</style>
2. 使用组件
<template>
<classtest />
<classtest></classtest>
<classtest></classtest>
</template>
<script setup>
import classtest from "./components/classtest.vue";
</script>
<style scoped>
</style>
3. 注册全局组件
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
//引入组件地址
import classtest from "./components/classtest.vue";
//引入组件地址
import classtest2 from "./components/classtest2.vue";
createApp(App)
//此处注意次序,
//1.先注册App.vue组件
//2.App组件注册完毕,在注册其下的子组件(子组件之间不分先后次序)
//3.最后在进行挂载
.component('classtest',classtest)
.component('classtest2',classtest2)
//挂载
.mount('#app')
4. 注册局部组件
①使用<script setup>
单文件组件
<template>
<classtest />
<classtest></classtest>
</template>
<script setup>
import classtest from "./components/classtest.vue";
</script>
<style scoped>
</style>
②不使用<script setup>
单文件组件
<template>
<classtest />
<classtest></classtest>
</template>
<script>
import classtest from "./components/classtest.vue";
export default {
components:{
classtest
},
setup() {
}
}
</script>
<style scoped>
</style>
在整个指引中,我们都使用 PascalCase 作为组件名的注册格式,这是因为:
PascalCase 是合法的 JavaScript 标识符。这使得在 JavaScript 中导入和注册组件都很容易,同时 IDE 也能提供较好的自动补全。
<PascalCase />
在模板中更明显地表明了这是一个 Vue 组件,而不是原生 HTML 元素。同时也能够将 Vue 组件和自定义元素 (web components) 区分开来。
在单文件组件和内联字符串模板中,我们都推荐这样做。但是,PascalCase 的标签名在 DOM 内模板中是不可用的,详情参见 DOM 内模板解析注意事项。
为了方便,Vue 支持将模板中使用 kebab-case 的标签解析为使用 PascalCase 注册的组件。这意味着一个以 MyComponent 为名注册的组件,在模板中可以通过 <MyComponent>
或 <my-component>
引用。这让我们能够使用同样的 JavaScript 组件注册代码来配合不同来源的模板。