vue3相比vue2更加輕量黍判,區(qū)別之一就是使用setup代替了data,methods,還有響應式數(shù)據(jù)類型ref,reactive的使用篙梢。
新建一個index.vue
<template> html元素 </template>
<script setup lang="ts"> ts邏輯 </script>
<style scoped lang="scss"> 樣式 </style>
vue3聲明使用變量不再需要this指向顷帖,例如
import { ref, } from 'vue';
const flag = ref<boolean>(false);
flag.value = true;
import { reactive, } from 'vue';
interface userInfoType {
[key:string]: any;
}
const userData:userInfoType = reactive({
userName: '',
password: '',
});
/**
* 修改
* @param {string} type 屬性名
* @param {string} value 屬性值
* @returns {void}
*/
const changeValue = (type:string,value:string): void => {
userData[type] = value;
};
// 對某個屬性值修改
userData.password = 'xxx';
兩者區(qū)別在于
推薦reactive定義復雜的數(shù)據(jù)類型的數(shù)據(jù),如對象類型庭猩;
ref推薦定義基本數(shù)據(jù)類型窟她。在使用ref定義的數(shù)據(jù)時,需要加.value蔼水。
setup內(nèi)箭頭函數(shù)的寫法
const loginFn = ():void => {
console.log('hello');
};
vue2和vue3的生命周期對比
Vue2--------------vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivate
//生命周期函數(shù)寫法
import { onMounted, } from 'vue';
onMounted(() => {
console.log('hello');
});