VUE3的學習和使用(一)
阿新 • • 發佈:2022-03-18
vue3相比vue2更加輕量,區別之一就是使用setup代替了data,methods,還有響應式資料型別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';
兩者區別在於
推薦reactive定義複雜的資料型別的資料,如物件型別;
ref推薦定義基本資料型別。在使用ref定義的資料時,需要加.value。
setup內箭頭函式的寫法
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 //生命週期函式寫法 import { onMounted, } from 'vue'; onMounted(() => { console.log('hello'); });