目录
全局组件
全局指令
局部指令
全局组件
全局组件是在main.js中注册的,通过app实例.component创建
main.js
import { createApp } from 'vue'
import App from './App.vue'
//导入组件
import CustormComp from './components/CustormComp.vue'
// 创建App实例挂载到id为app的dom元素
const app=createApp(App)
//注册组件
// 全局组件->相当于vue2的Vue.component()
app.component('CustormComp',CustormComp)app.mount('#app')
App.vue
<template><div><h2>hellow,world</h2><custorm-comp></custorm-comp></div>
</template><script setup></script><style lang="scss" scoped></style>
局部组件,就是vue的导入注册使用,只不过再setup()语法糖下,不需要注册组件
全局指令
main.js
import { createApp } from 'vue'
import App from './App.vue'import CustormComp from './components/CustormComp.vue'
const app=createApp(App)// 注册全局指令
app.directive('color',{mounted(el,binding){el.style.backgroundColor=binding.value},updated(el,binding){el.style.backgroundColor=binding.value}
})// 钩子函数只用到mounted和updated可以简写为下面的函数
// 假如需要用到其他钩子函数或mounted和updated执行不同逻辑要写成对象//app.directive('color',(el,binding)=>{// el.style.backgroundColor=binding.value
//})
使用 App.vue
<template><div><h2 v-color="color">hellow,world</h2><custorm-comp></custorm-comp></div>
</template><script setup>
import {ref} from 'vue'
const color=ref('pink')</script><style lang="scss" scoped></style>
局部指令
App.vue
<template><div><h2 v-color="color">hellow,world</h2><input type="text" v-focus><custorm-comp></custorm-comp></div>
</template><script setup>
import {ref} from 'vue'
const color=ref('pink')
//局部指令
const vFocus={mounted(el){el.focus()}
}</script><style lang="scss" scoped></style>