1.创建项目(vite + vue3)
npm init vite@latest vue-demo -- --template vue
2.vue3的基本写法
<script setup>
import { ref, watch, watchEffect, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
// ref定义变量
const count = ref(1)
//定义函数
const onClick = ()=>{
count.value++
}
// props接受父组件参数,父组件写法和vue2一样
defineProps({
msg: String,
})
// watch 指定监听对象
watch(count, (newVal)=>{
console.log(`count值改变了:${count.value}`)
})
// 自动监听(不需要指定监听对象)
const num = ref(0)
watchEffect(()=>{
num.value = count.value
console.log('监听到count值改变,num也改变:', num.value)
})
/*
声明周期函数
setup中不能使用onBeforeCreate, onCreated
destroy的两个函数换成了unMounted
*/
onBeforeMount(()=>{})
onMounted(()=>{})
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="onClick">count is {{ count }}</button>
</div>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>