1. router路由跳转
描述1: vue 3+中setup函数中,并没有this或者概念,那么要怎么实现vue 2+中 this.$router 路由跳转
解决:vue-router 提供了 useRouter
//引入路由函数
import { useRouter } from "vue-router";
//使用
setup() {
//初始化路由
const router = useRouter();
router.push({
path: "/"
});
// 获取当前路由
// router.currentRoute.value.fullPath
return {};
}
描述2: vue3如何监听路由变化
import { useRouter } from "vue-router"
// 监听路由变化
setup(){
const router = useRouter()
watch(
() => ruoter.currentRoute.value.fullPath,
(val, oldVal) => {
// ...
}
)
}
2. computed 的使用
import { computed, ref } from 'vue'
export default {
setup() {
const count = ref(0)
const num = computed(() => {
return +age.value + 1
})
return {
count,
num
}
}
}
3. watch的使用
方式1:侦听reactive定义的数据
setup() {
const state = reactive({ nickname: "xiaofan", age: 20 });
setTimeout(() => {
state.age++;
}, 1000);
// 修改age值时会触发 watch的回调
watch(
() => state.age,
(curAge, preAge) => {
console.log("新值:", curAge, "老值:", preAge);
}
);
return {
...toRefs(state),
};
},
方式2:侦听ref定义的数据
const year = ref(0);
setTimeout(() => {
year.value++;
}, 1000);
watch(year, (newVal, oldVal) => {
console.log("新值:", newVal, "老值:", oldVal);
});
问题 1: A watch source can only be a getter/effect function,a ref ,a reactive object, or an array of these types.
const state = ref(0)
watch(
// 如果state是ref对象,侦听source应该为 state,否则会出现如上警告
state,
(count, prevCount) => {
console.log(count, prevCount);
}
);
4. vue3中父组件调用子组件方法
描述: 在 setup() 内部,this 不会是该活跃实例的引用,因为 setup() 是在解析其它组件选项之前被调用的。因此要想调用子组件的方法,还是要通过 vue2+ $refs。
案例:
<template>
<input ref="input" />
</template>
<script>
import { defineComponment } from 'vue'
export default defineComponent({
setup(){
},
methods: {
this.$refs.input.***() // 调用子组件方法
}
})
</script>