Vue3之script setup的用法记录
在Vue3中,在<script setup>中
一、父组件给子组件传参
父组件
<mainForm v-if="Object.keys(dataSource).length != 0" :dataSource="dataSource" @handle="handle" />
子组件
const props = defineProps({
dataSource: Object,
});
const { dataSource } = toRefs(props);
二、子组件调用父组件
子组件
<template> <van-nav-bar title="XXX" left-text="返回" left-arrow @click-left="onClickLeft" ></van-nav-bar> </template> <script setup> import { defineComponent, reactive, ref } from "vue"; const emit = defineEmits(["onClickLeft"]); const onClickLeft = () => { emit("onClickLeft"); }; </script> <style> </style>
父组件
<NavBar @onClickLeft="onClickLeft" />
在父组件中可重写onClickLeft方法实现方法的多态性。
三、父组件调用子组件
子组件
defineExpose({
onSubmit
});
父组件
<upload-customer-appendix ref="appendix" ></upload-customer-appendix>
父组件调用方式为:
const appendix = ref(); const uploadCustomerAppendixOk = () => { appendix.value.onSubmit(); };
注:若父子组件传值或相互调用出现undefined,可能是因为父组件或子组件用的不是<script setup>,没有return对应的变量导致的。
四、等待DOM加载完再操作
如绘制图表,可用:
import { onMounted, ref } from "vue"; onMounted(() => { //do stuff });
五、页面间传参
导入:
import { useRouter, useRoute } from "vue-router";
传参方式:
router.push({ path: "/newCollect", query: { mode: "edit", }, });
获取router和route
const router = useRouter();
const route = useRoute();
取参方式:
const mode = router.currentRoute.value.query.mode;
或
route.query.mode
六、监控变量变化
引入watch
import { watch } from "vue";
监听变量变化
watch(xx, (newVal, oldVal) => { //do stuff });
监听对象属性变化
const formState = ref({ publishType: sessionStorage.publishType ? sessionStorage.publishType : "published" }); watch(() => formState.value.publishType, val => { sessionStorage.publishType = formState.value.publishType });
监听传参变化
watch(() => props.xx, val => {
init();
});
七、<component>的使用
使用示例:
<component :is="compCorresponding[selectedKeys[0]]" />
JS为:
const compCorresponding = {
projectDetail: EpProjectDetail,
appCreate: ProjectAppList,
pageSet: EpPageList,
dataBase: DataBaseList,
libraryTableStructure: LibTableStructure,
dataManagement: DataManagement,
};
其中,右边的为组件名,需在该文件中导入组件。