vue3 常見問題彙總
簡介:vue3 beta 已經出來一段時間了,最近剛好有時間,就練了練手,練手過程中遇到的問題,總結如下
本文 github 源碼地址
下面是問題
vue3 如何註冊全局組件
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 如何註冊全局自定義指令
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 如何全局混入
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 全局混入
app.mixin({
beforeCreate() {
console.log('我是全局mixin')
}
})
app.mount('#app')
vue3 如何全局掛載全局屬性和方法
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 如何註冊插件
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 註冊插件
class plugin {
static install(_vue) {
// 混入
_vue.mixin({
beforeCreate() {
console.log('我是plugin')
}
})
}
}
app.use(plugin)
app.mount('#app')
vue3 全局註冊過濾器 filter
哈哈貌似 vue 3 放棄了過濾器,暫時無法註冊
vue3 setup 函數裏如何拿到 vue-router 的$router,$route
import { getCurrentInstance, unref } from 'vue'
export default {
setup() {
// 拿到當前組件 this(ctx)
const { ctx } = getCurrentInstance()
// 拿到 $router
const $router = ctx.$router
// 拿到 $route
const $route = unref(ctx.$router.currentRoute)
}
}
vue3 setup 函數裏如何拿到 vuex 的$store
import { getCurrentInstance, onMounted } from 'vue'
export default {
setup() {
// 拿到當前組件 this(ctx)
const { ctx } = getCurrentInstance()
// console.log(ctx.$store)
// 在這裏這樣是拿不到的,因爲$store在beforeCreate生命週期裏注入,而setup函數在beforeCreate之前執行
// 此鏈接的文章裏有介紹 https://blog.csdn.net/qq_39953537/article/details/105703894
onMounted(() => {
console.log(ctx.$store)
})
}
}
參考鏈接