一、定义基本类型
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);
(2) 数组对象
interface MyData {
name: string;
age: number;
}
const myArray: MyData[] = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
];
const myRef = ref<MyData[]>(myArray);
console.log(myRef.value[0].name);
console.log(myRef.value[0].age);
myRef.value[1].name = 'Charlie';
myRef.value[1].age = 35;
console.log(myRef.value[1].name);
console.log(myRef.value[1].age);
(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;
console.log(myRef.value.name);
console.log(myRef.value.age);
console.log(myRef.value.hobbies);
console.log(myRef.value.address.street);
console.log(myRef.value.address.city);