期待了很久的vue3,一發布就上手體驗了一把,這里記錄幾個自己碰到的網上不常見的小坑~
自定義全域引數
定義:
// main.js
const app = createApp(App)
app.config.globalProperties.$test = 'test'
除了setup()需要先獲得實體,其他地方可以直接通過$test使用:
<tempalte>
<div>{{ $test }}</div>
</tempalte>
<script>
import { getCurrentInstance } from 'vue'
export default {
setup() {
const test = getCurrentInstance()?.appContext.config.globalProperties.$test
console.log('test===')
console.log(test)
},
}
</script>
Vite通過alias別名參考
在webpack中,配置src的別名為@,可以這么寫:
// 參考src/views/PageOne.vue
import PageOne from '@/views/PageOne.vue'
如果使用Vite,則需要做以下修改:
// vite.config.js
module.exports={
alias: {
'/@/': path.resolve(__dirname, './src'),
},
}
// tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["src/*"],
"/@/views/*": ["src/views/*"]
}
}
}
import PageOne from '/@/views/PageOne.vue'
更加規范的props和emits
在vue3中,父子組件傳值的props和emits寫法更加規范(命名更統一),體現在:
v-model的變化
<template>
<child-component v-model:value="myValue"></child-component>
</template>
v-model:value等同于props:'value'和emits('update:value')
- 需要指定
emits
為了便于管理,建議在emits中定義所有用到的emit
export default {
emits: ['update:value', 'otherEmit'],
setup(props, { emit }) {
emit('update:value')
emit('otherEmit')
},
}
跟蹤attrs和slots
本來以為可以通過watch()函式直接watch(()=>attrs.xxx),結果是不行,這里官網有些,一開始自己沒注意:
attrs 和 slots 是有狀態的物件,它們總是會隨組件本身的更新而更新,這意味著你應該避免對它們進行解構,并始終以 attrs.x 或 slots.x 的方式參考 property,請注意,與 props 不同,attrs 和 slots 是非回應式的,如果你打算根據 attrs 或 slots 更改應用副作用,那么應該在 onUpdated 生命周期鉤子中執行此操作,
所以要回應式處理attrs和slots,就需要:
import { onUpdated, reactive, watch, watchEffect } from 'vue'
export default {
setup(props, { attrs }) {
function _handleAttrsChange() {
console.log('attrs===')
console.log(attrs)
}
onUpdated(() => {
_handleAttrsChange()
})
// props和data可以正常使用watch函式
watchEffect(() => {
console.log('propsXxx===')
console.log(props.xxx)
})
const state = reactive({ count: 0 })
watch(() => state.count, (now, old) => {
//
})
},
}
VueRouter不能直接使用含有props的組件
我有一個地址串列AddressList,需要通過props接收父組件引數:
// router.js
export default {
name: 'AddressList',
props: {
propName: String,
},
}
通過組件呼叫,沒有問題,但是配置為vue-router項時會報錯:
export default {
routes: [
{
path: 'address_list',
component: () => import( 'AddressList.vue'),
},
],
}
既然不能直接將組件作為route使用,那么就在其他頁面中呼叫就好了
// router.js
export default {
routes: [
{
path: 'address_list',
component: () => import( 'Page.vue'),
meta: { component: 'AddressList' },
},
],
}
<!--Page.vue-->
<template>
<component :is="component" />
</template>
<script lang="ts">
import AddressList from '/@/views/AddressList.vue'
import { defineComponent } from 'vue'
export default defineComponent({
name: 'Page',
components: { AddressList },
computed: {
component () {
return this.$route.meta.component
},
},
})
</script>
覺得寫得不錯的話,請用你們發財的小手點個贊叭!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/259268.html
標籤:其他
