生命周期变更
结构全部使用setup语法糖
<script setup name="Config">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, refreshCache } from "@/api/system/config";
const { proxy } = getCurrentInstance();
const { sys_yes_no } = proxy.useDict("sys_yes_no");
const configList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const data = reactive({
form: {},
queryParams: {
pageNum: 1,
pageSize: 10,
configName: undefined,
configKey: undefined,
configType: undefined
},
rules: {
configName: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
configKey: [{ required: true, message: "参数键名不能为空", trigger: "blur" }],
configValue: [{ required: true, message: "参数键值不能为空", trigger: "blur" }]
}
});
</script>
响应式
ref 与 reactive
计算属性 侦听器
watch(()=>layerContrast.value,
(newValue: string , oldValue: any) => {
console.log('新值')
},
{ immediate: true,deep:true }
)
const type = computed(() => {
if (layerContrast.value) {
return 'a'
}
return 'b'
})
vue2和vue3 watch区别 http://t.csdnimg.cn/PoiTj
hooks
vue3 中的 hooks 就是函数的一种写法,就是将文件的一些单独功能的js代码进行抽离出来,放到单独的js文件中,或者说是一些可以复用的公共方法/功能。 hooks 更清楚复用功能代码的来源, 更清晰易懂。
示例
export function useInitCesiumOperationPanel(domId: string, centerJDWD: _JDWD) {
const data=ref(null)
onMounted(()=>{
let map = initMap(domId);
let graphicLayer = new mars3d.layer.GraphicLayer({
allowDrillPick: true,
});
map.addLayer(graphicLayer);
data.value = 1
})
return data
}
vueuse 文档useMouse | VueUse中文文档
pinia
export const useChartStore = defineStore("chart", () => {
const chartData = reactive<ChartData>({
dataSource: GDTDataSourceType.BUILDING,
subTitle: "",
REPLYLIST: [],
ngList: [],
filterGroupInfo: null,
KSSJC: "",
});
function chartDataChange(params: Partial<ChartData>): void {
let key: keyof typeof chartData;
for (key in params) {
copyProp(chartData, params, key);
}
}
function copyProp<T, K extends keyof T>(dst: T, src: T, key: K) {
dst[key] = src[key];
}
function changeXddwData(params: typeof xddwUpdateData) {
Object.assign(xddwUpdateData, params);
}
const personList = reactive<_SBBH[]>([]);
return {
chartData,
chartDataChange,
personList,
changeXddwData,
};
});
使用方法
import { useChartStore } from "@/stores/chart";
const chartStore = useChartStore();
chartStore.chartDataChange({
isShow: true,
type: CHART_TYPE.QTGD,
fzid: buildNews.value?.FZID,
dataSource: GDTDataSourceType.BUILDING,
});
ts
<script setup lang="ts">
import { ref, computed } from "vue";
const isDone: boolean = false;
const a11: number = 1;
const a = ref<string>("");
const b = ref<boolean>(true);
const c = ref<number>(1);
const d = ref<null>(null);
const e = ref<undefined>(undefined);
const f = ref<unknown>(1);
const g = ref<any>(1);
const h = ref<number | string>(1);
const i = ref<string[]>(["1"]);
const j = ref<string[] | number[]>([1, 1]);
const k = ref<{ type: number; name: string }>({ type: 1, name: "啊" });
const i1 = ref<Array<string>>(["1"]);
const aaa = ref<(number | string | null)[]>(["1", 1, null]);
func("1");
function func(val: string | number): string {
return (val as string).substring(0, 1);
}
interface Person {
name: string;
age?: number;
}
let tom: Person = {
name: "Tom",
age: 25,
};
let fibonacci: Person[] = [{ name: "1", age: 2 }];
</script>
在线转ts工具在线json转ts类型-forrest
枚举 命名统一大写下划线 属性大写
/**
* 语言类型 枚举
*/
export enum LangType {
/**
* 简体中文
*/
ZH = 0,
/**
* 繁体中文(香港、台湾等地区)
*/
ZHHK = 1,
/**
* English英文 en
*/
EN = 2
}
正确示范
ts基础
基本类型
//布尔值
const isBoolean:boolean = false;
//数字
const decLiteral: number = 6;
//字符串 模版字符串
const name: string = "bob";
//数组
const list:number[]=[1,2,3]; let list: Array<number> = [1, 2, 3];
// 元组
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error
//枚举 默认0,1,2
enum Color {
Red,
Green,
Blue
}
console.log(Color) //{ 0: 'Red', 1: 'Green', 2: 'Blue', Red: 0, Green: 1, Blue: 2 }
console.log(Color.Red) //0
console.log(Color['0']) //'Red'
//任意值
any //我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查
const list: any[] = [1, true, "free"];
//空值
//一个函数没有返回值时,你通常会见到其返回值类型是void
function warnUser(): void {
alert("This is my warning message");
}
const unusable: void = undefined; //他只能赋值null undfined
//Null 和 Undefined
const u: undefined = undefined;
const n: null = null;
//类型断言
as语法 告诉编译器这个类型
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
尖括号
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
接口(interface)
为你的代码或第三方代码进行定义
///基础写法
function printLabel(labelledObj: { label: string,val?:number }) {
console.log(labelledObj.label);
}
//定义接口描述
interface LabelledValue {
label: string;
val?:number
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
//?: 可选属性 接口里的属性 有些是只在某些条件下存在,或者根本不存在。
//只读属性
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
函数(function)
function add(x: number, y: number): number {
return x + y;
}
let myAdd = function(x: number, y: number): number { return x + y; };
//...剩余参数
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
pick。 omit
type OriginalType = {
name: string;
age: number;
address: string;
};
type PickedType = Pick<OriginalType, 'name' | 'age'>;
// PickedType 是 { name: string, age: number }
type OmittedType = Omit<OriginalType, 'address'>;
// OmittedType 是 { name: string, age: number }
TypeScript 与组合式 API
props(两种写法)
<script setup lang="ts">
//defineProps() 宏函数支持从它的参数中推导类型:
const props = defineProps({
foo: { type: String, required: true },
bar: Number
})
props.foo // string
props.bar // number | undefined
</script>
//第二 泛型
<script setup lang="ts">
interface Props {
foo: string
bar?: number //可以有可以没有
}
const props = defineProps<Props>()
</script>
//Props 解构默认值
//当使用基于类型的声明时,我们失去了为 props 声明默认值的能力。这可以通过 withDefaults 编译器宏解决:
************************************************************ 推荐
<script setup lang="ts">
export interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
</script>
子传父
const emit = defineEmits(["goBack"]);
const goBack = () => {
emit("goBack");
};
自定义Hook:
- 将可复用功能抽离为外部ts文件
- 函数名/文件名以use开头,形如:useXX
- 引用时将响应式变量或者方法显式解构暴露出来如:const {nameRef,Fn} = useXX()(在setup函数解构出自定义hooks的变量和方法)
import { reactive } from "vue";
export function useVwSize() {
const data = reactive({
width: 0,
height:0
})
const getViewportSize = () => {
data.width = document.body.clientWidth;
data.height = document.body.clientHeight;
}
return {
data,
getViewportSize
}
}
<script setup lang="ts">
import { useVwSize } from "@/hooks";
const { data, getViewportSize } = useVwSize();
</script>
<template>
<button @click="getViewportSize">获取窗口大小</button>
<div>
<div>宽度 : {{ data.width }}</div>
<div>宽度 : {{ data.height }}</div>
</div>
</template>
......
倒计时
/* 倒计时
* @param {Number} second 倒计时秒数
* @return {Number} count 倒计时秒数
* @return {Function} countDown 倒计时函数
* @example
* const { count, countDown } = useCountDown()
* countDown(60)
* <div>{{ count }}</div>
*/
import { onBeforeMount } from "vue";
export function useCountDown() {
const count = ref<number>(0);
type Timer = ReturnType<typeof setInterval>;
let timer: Timer | null = null;
const countDown = (second:number, ck:()=>void) => {
if (count.value === 0 && timer === null) {
ck();
count.value = second;
timer = setInterval(() => {
count.value--;
if (count.value === 0) {
clearInterval(timer);
}
return
}, 1000);
}
};
onBeforeMount(() => {
timer && clearInterval(timer);
});
return {
count,
countDown,
};
}
<script setup lang="ts">
import {useCountDown} from "@/hooks";
// 倒计时
const { count, countDown } = useCountDown();
</script>
学习网址
纯干货分享 球球看过的小伙伴给个关注啦~~
穷苦码字员在线给跪~~