vue3 常见问题汇总

vue3 如何注册全局组件

1
2
3
4
5
6
7
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 注册全局组件
import SaveButton from '@/globalComponents/SaveButton'
app.component('SaveButton', SaveButton)
app.mount('#app')

vue3 如何自定义全局指令

1
2
3
4
5
6
7
8
9
10
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 注册全局自定义指令 `v-focus`
app.directive('focus', {
inserted: function (el) {
el.focus()
},
})
app.mount('#app')

vue3 如何全局混入

1
2
3
4
5
6
7
8
9
10
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 全局混入
app.mixin({
beforeCreate() {
console.log('我是全局mixin')
},
})
app.mount('#app')

vue3 如何挂载全局属性和方法

1
2
3
4
5
6
7
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
// 全局ctx(this) 上挂载 $axios
app.config.globalProperties.$axios = axios
app.mount('#app')

vue3 setup 函数里如何拿到 vue-router 的$router,$route

通过getCurrentInstance或者useRoute ,useRouter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { getCurrentInstance, unref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export default {
export default {
setup() {
// 拿到当前组件 this(ctx)
const { ctx } = getCurrentInstance()
// 拿到 $router
// const $router = useRouter()
const $router = ctx.$router
// 拿到 $route
// const $route = useRoute()
const $route = unref(ctx.$router.currentRoute)
}
}
thank u !