# 1.ref 默认修改是否响应式?
App 为根组件 下面 Home 例子都被此组件引用
// App.vue | |
<template> | |
<div> | |
<home></home> | |
</div> | |
</template> | |
<script> | |
import Home from "./Home.vue"; | |
export default { | |
components: { | |
Home, | |
}, | |
}; | |
</script> | |
<style scoped> | |
</style> |
// Home.vue | |
<template> | |
<div> | |
<!-- --> | |
<h2>{{ info }}</h2> | |
<button @click="changeInfo">修改age</button> | |
</div> | |
</template> | |
<script> | |
// 默认情况下 ref (reactive) 会进行深层次的响应式 | |
import { ref } from "vue"; | |
export default { | |
setup() { | |
const info = ref({ name: "Neko", age: 16 }); | |
console.log("改变之前:", info.value.name); | |
const changeInfo = () => { | |
info.value.name = "Nico"; | |
console.log("改变之后:", info.value.name); | |
}; | |
return { | |
info, | |
changeInfo, | |
}; | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
# 2.shallowRef 浅层响应式
// Home.vue | |
<template> | |
<div> | |
<!-- --> | |
<h2>{{ info }}</h2> | |
<button @click="changeInfo">修改age</button> | |
</div> | |
</template> | |
<script> | |
// 默认情况下 ref (reactive) 会进行深层次的响应式 | |
import { ref, shallowRef } from "vue"; | |
export default { | |
setup() { | |
// 使用 shallowRef 创建一个浅层的 ref 对象,数据发生了改变但是并不是响应式的 | |
const info = shallowRef({ name: "Neko", age: 16 }); | |
console.log("改变之前:", info.value.name); | |
const changeInfo = () => { | |
info.value.name = "Nico"; | |
console.log("改变之后:", info.value.name); | |
}; | |
return { | |
info, | |
changeInfo, | |
}; | |
}, | |
}; | |
</script> | |
<style scoped> | |
</style> |
参考结果:
# 3.triggerRef 强制触发响应式
// Home.vue | |
<template> | |
<div> | |
<!-- --> | |
<h2>{{ info }}</h2> | |
<button @click="changeInfo">修改age</button> | |
</div> | |
</template> | |
<script> | |
// 默认情况下 ref (reactive) 会进行深层次的响应式 | |
import { ref, shallowRef, triggerRef } from "vue"; | |
export default { | |
setup() { | |
// 使用 shallowRef 包裹,数据发生了改变但是并不是响应式的 | |
const info = shallowRef({ name: "Neko", age: 16 }); | |
console.log("改变之前:", info.value.name); | |
const changeInfo = () => { | |
info.value.name = "Nico"; | |
// 手动触发 shallowRef 相关联的副作用 triggerRef 里需要传入一个 ref | |
triggerRef(info); | |
console.log("改变之后:", info.value.name); | |
}; | |
return { | |
info, | |
changeInfo, | |
}; | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
# 4. 总结
- shallowRef 生成的响应式数据并不会发生变化
- triggerRef 将上面用 shallowRef 生成响应式数据
- triggerRef 的作用就是将 ref 生成的数据强制在页面更新,手动执行与 shallowRef 关联的任何效果。