持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
1.defineProps【定义组件的参数,声明props】
<script setup lang="ts">
interface IParams {
value: string, //值
label: string, //文本
children?: string, //数据的层级
disabled?:string,
multiple?:boolean,
list?:string//自定义添加的属性字段,用于获取数据时的配置
}
const props = defineProps({
modelValue: { //值
type: Array,
required: true,
},
data: { //渲染数据
type: Array,
default () {
return [{
value: '1',
label: '选项1',
children: [
{
value: '1-1',
label: '选项1-1',
}
]
}]
}
},
query: { //请求参数
type: Object,
default () {
return {}
}
},
props: { //同cascader的配置
type: Object as PropType < IParams >
},
method: {
type: String,
default: 'post'
},
})
</script>
2. defineEmits【声明组件中的事件】
<script setup lang="ts">
const emits = defineEmits(['update:modelValue'])
const modelValueSet = computed({
get():any[]{
return modelValue.value
},
set(val:any[]) {
emits('update:modelValue', val)
}
})
</script>
3. watch
- 【监听上面props中data的变化】
<script setup lang="ts">
import {ref} from 'vue'
const curData = ref([])
watch(()=>props.data, (newVal, oldVal) => {
curData.value = newVal
}, {
immediate: true//立即触发
})
</script>
4. 插槽slot和subpense的结合使用
- 【subpense:内置组件,用来对异步依赖的处理】
# own-suspense组件
<template>
<suspense>
<template #default><slot></slot></template>
<template #fallback>
<div class="loading" :loading="true" element-loading-text="`加载中......`"></div>
</template>
</suspense>
</template>
# index.vue的使用
<script>
const tabsComponents: any = {
container: markRaw(defineAsyncComponent(() => import('./container.vue'))),
logic: markRaw(defineAsyncComponent(() => import('./logic.vue')))
}
const
</script>
<own-suspense>
<component :is="tabsComponents.container"></component>
</own-suspense>
4. provide和inject 【多层级组件的数据】
# parent.vue组件
<script setup lang="ts">
import {reactive} from 'vue'
interface formObjectI{
no:string,
name:string
}
const formObject: formObjectI = reactive({ no: '', name: ''})
provide('formObject', formObject)
</script>
<template>
<son></son>
</template
# son.vue组件
<script setup lang="ts">
//第2个参数是指为匹配到key时,使用的默认值
const formObject = inject<any>('formObject', { no: '',name:'' })
console.log(formObject)
</script>
5. nextTick 【等待下一次 DOM 更新】
<script setup lang="ts">
import {nextTick} from 'vue'
const formNameRef = ref();
const show = ref(false)
const formNameShow = () => { //显示
show.value = true;
nextTick(()=>{
formNameRef.value?.clearValidate()
});
}
</script>
<template>
<el-form ref="formNameRef">
...
</el-form>
</template>