一、app.component
全局注册组件
1.1、自定义一个组件
1.2、在main.ts
中全局注册自定义组件
// 引入 createApp 用于创建应用
import { createApp } from "vue";
// 引入 App 根组件
import App from './App.vue'
// 引入自定义的 Hello 组件
import Hello from "./components/Hello.vue";
// 创建一个应用
const app = createApp(App)
// 全局注册Hello组件。使用时以前面的命名为准。例如:<hw />
app.component('hw', Hello)
// 挂载整个应用到 app 容器中
// .mount() 方法应该始终在整个应用配置和资源注册完成后被调用。同时请注意,不同于其他资源注册方法,它的返回值是根组件实例而非应用实例。
app.mount('#app')
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
1.3、在其他组件中可使用自定义组件,无需引入。(使用时以全局注册时分配的命名为准)
<template>
<div class="app">
<!-- 对应注册时分配的命名。app.component('hw', Hello) -->
<hw />
</div>
</template>
<script setup lang="ts" name="App">
</script>
<style lang="scss" scoped>
.app {
width: 700px;
height: 200px;
margin: auto;
margin-top: 100px;
padding-top: 50px;
text-align: center;
background-color: bisque;
}
button {
margin-right: 10px;
background-color: darkorange;
}
</style>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
1.4、效果图。
二、app.directive
全局注册指令
2.1、在main.ts中全局注册自定义指令
// 引入 createApp 用于创建应用
import { createApp } from "vue";
// 引入 App 根组件
import App from './App.vue'
// 创建一个应用
const app = createApp(App)
// 自定义指定qqq
app.directive('qqq', (element, {value}) => {
element.innerText = value
element.style.color = 'red'
element.style.backgroundColor = 'yellow'
})
// 挂载整个应用到 app 容器中
// .mount() 方法应该始终在整个应用配置和资源注册完成后被调用。同时请注意,不同于其他资源注册方法,它的返回值是根组件实例而非应用实例。
app.mount('#app')
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
2.2、在其他组件中使用自定义指令
<template>
<div class="app">
<!-- 使用自定义指令 v-qqq,绑定zero -->
<h2 v-qqq="zero" />
</div>
</template>
<script setup lang="ts" name="App">
import { ref } from 'vue';
let zero = ref(777)
</script>
<style lang="scss" scoped>
.app {
width: 700px;
height: 200px;
margin: auto;
margin-top: 100px;
padding-top: 50px;
text-align: center;
background-color: bisque;
}
button {
margin-right: 10px;
background-color: darkorange;
}
</style>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.