TS在vue3中的初使用

一、定义基本类型

const myRef = ref<number>(1);
const myStringRef = ref<string>('hello');
const myBooleanRef = ref<boolean>(true);

二、引用类型

(1)对象

interface MyData {
  name: string;
  age: number;
}
const myData: MyData = {
  name: 'Alice',
  age: 25,
};
const myRef = ref<MyData | null>(null);
// 更新数据---赋值
myRef.value = myData;
console.log(myRef.value); // 输出:{ name: 'Alice', age: 25 }

(2) 数组对象

interface MyData {
  name: string;
  age: number;
}
const myArray: MyData[] = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
];
const myRef = ref<MyData[]>(myArray);
// 使用myRef.value访问数据
console.log(myRef.value[0].name); // 输出:Alice
console.log(myRef.value[0].age); // 输出:25
// 更新数据
myRef.value[1].name = 'Charlie';
myRef.value[1].age = 35;
console.log(myRef.value[1].name); // 输出:Charlie
console.log(myRef.value[1].age); // 输出:35

(3)对象属性为引用类型

interface MyData {
  name: string;
  age: number;
  hobbies: string[];
  address: {
    street: string;
    city: string;
  };
}
const myObject: MyData = {
  name: 'Alice',
  age: 25,
  hobbies: ['reading', 'hiking'],
  address: {
    street: '123 Main St',
    city: 'Anytown',
  },
};
const myRef = ref<MyData | null>(null);
// 更新数据
myRef.value = myObject;

// 使用myRef.value访问数据
console.log(myRef.value.name); // 输出:Alice
console.log(myRef.value.age); // 输出:25
console.log(myRef.value.hobbies); // 输出:['reading', 'hiking']
console.log(myRef.value.address.street); // 输出:123 Main St
console.log(myRef.value.address.city); // 输出:Anytown

你可能感兴趣的:(vue.js,javascript,前端)