vue3组合式API写法<script setup>
废话不多说,直接上干货:
<template>
<p>{{state.totalCount}}</p>
<button @click="onClickHandle">点击我数字加</button>
<button @click="routerHandle">路由跳转/button>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, getCurrentInstance, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const { proxy } = getCurrentInstance() //vue实例,类似选项式写法中this,如果全局添加了message,则可以proxy.$message('消息内容')
const router = useRouter();
const route = useRoute();
const state = reactive({
routerQuery: computed(() => route.query),//路由携带过来的参数
totalCount: 0,
watchVal1: '',
watchVal2: '',
})
onMounted(() => {
//相当于vue2或者选项式写法中生命周期mounted
})
watch(() => [state.watchVal1, state.watchVal2], ([newVal1, oldVal1], [newVal2, oldVal2]) => {
if(!newVal1 && newVal1 != oldVal1) {
//要实现的方法
}
// val2同上
})
const onClickHandle = () => {
state.totalCount++;
}
const routerHandle = () => {
router.push('path')//path自己的路由
}
const onUnmounted(() => {
//相当于vue2或者选项式写法中生命周期unmounted
})
</script>
<style>
</style>
到这里基本完成,然后呢,就没有然后了。。。
想要深入了解,我们可以一起交流,自己多看文档多学吧!!!