skip to content
天真笔录

vue3 复习

/ 2 min read

composition api

  1. ref
  • 定义基础类型
import { ref } from "vue";
const name = ref("tianzhen");
const age = ref(10);
  1. reactive
  • 定义引用类型
import { reactive } from "vue";
const obj = reactive({
	name: "tianzhen",
	age: 20,
});
const arr = reactive([10, 20]);

解构

  • reactive 在结构后会失去响应式,但不绝对
  • 如果是深层,获取深层中key对应value,此时value还是reactive对象,解构后还是具有响应式
import(reactive, isReactive);
let { name } = reactive({ name: { z: "info" } });
name.z = "tianzhen";
console.log(isReactive(name)); // true
  1. toRef
import { reactive, toRef } from "vue";
const obj = reactive({
	name: "tianzhen",
	age: 20,
});
const sexRef = toRef(obj, "sex");
sexRef.value = "man";
obj.sex; // man
  1. setup 参数

props 等同于vue2->props

context { attrs, emit, slots } = context

  1. computed
import { ref, computed } = 'vue'

const count = ref(0)
const countFive = computed(() => {
	return count.value + 5
})
const countFive = coumputed({
	get() {},
	set() {},
});
  1. watch
import { watch } from "vue";
const count = ref(0);
watch(count, (current, prev) => {});
const nameObj = reactive({ name: "tianzhen" });
// 错误
watch(nameObj.name, () => {});
// 正确
watch(() => nameObj.name);
// 监听多个
watch(
	[() => nameObj.name, () => nameObj.englishName],
	([currentName, currentEnglishName], [prevName, prevEnglishName]) => {},
);
  1. watchEffect
  • 立即执行,没有惰性
  • 不需要传递需要侦听的内容,会自动感知代码依赖,不需要传递参数,只需要一个回调函数
  • 不能获取之前的值
const stop = watchEffect(() => {
	console.log(nameObj.name);
});

取消侦听:stop()

  1. 生命周期

onRenderTracked

  • 每次渲染后重新收集响应式依赖

onRenderTriggered

  • 每次触发页面重新渲染时自动执行