最近用vue3 重构vue2.x的项目,真是一坑未平,一波又起,话不多说 上代码
<template> <div>{{ loadingStatus }}</div> </template> ... setup(props, context) { // @ts-ignore const { proxy } = getCurrentInstance(); const typeClassName = computed(() => { return "xb-" + props.type; }); let loadingStatus = ref(false); const handleClick = () => { if (props.autoLoading) { loadingStatus= true; } context.emit("click", () => { loadingStatus= false; }); }; return { loadingStatus, handleClick }; }
乍一看是不是没什么问题,但是视图上loadingStatus依然是false,为什么呢,setup内部打印出为true,于是我看文档突然。。。
因为我们在使用Vue3的时候,通常使用ref来监听一些简单数据类型如数字、字符串、布尔等。你可能注意到一种现象,是更改ref的值的时候,需要使用ref.value的形式,(在template中使用ref时,Vue自动帮我们添加.value了,所以不需要我们手动添加),看起来很神奇,为什么会有一个.value呢?是因为ref本质上是一个包装过后的reactive。在你去定义ref的时候,Vue会内部帮我们包装一下。
对于ref而言,因为ref是包装过的reactive,所以使用reactive就可以定义ref:
let age = ref(18) // 等价于 let age = reactive({value: 18})
function ref(val) { return reactive({value: val}) }
所以最终代码:
<template> <div>{{ loadingStatus }}</div> </template> ... setup(props, context) { // @ts-ignore const { proxy } = getCurrentInstance(); const typeClassName = computed(() => { return "xb-" + props.type; }); let loadingStatus = ref(false); const handleClick = () => { if (props.autoLoading) { loadingStatus.value= true; } context.emit("click", () => { loadingStatus.value= false; }); }; return { loadingStatus, handleClick }; }
一句话:修改ref需要.value 而 reactive 则不用