[Vue] Reactive note
<template>
<div>
count: {{ count }}
</div>
<div>
doubled: {{ doubledCount }}
</div>
<button @click="increase">increase</button>
</template>
<script setup>
import {computed, ref, watch, watchEffect} from "vue"
const props = defineProps({
count: Number
})
const emit = defineEmits(['update:count'])
function increase() {
emit('update:count', props.count + 1)
}
// 1: No
// Reactive: Function bind to a value
// Function: vue2: watcher, vue3: effect, render, computed
// Value: 1. must be reactive data, 2. must be used inside the Function
// Not value bind to a value, this is not possible in javascript
// therefore props.count change will not trigger the doulbedCount to change
// const doulbedCount = ref(props.count * 2)
// 2: Yes
// Function: watchEffect
// value: props.count, doubledCount
// props.count is used inside the watchEffect function, so it's correct
// props.count change will trigger the watchEffect to re-run
// doubledCount is also reactive, so it will trigger the render
//const doubledCount = ref(0)
//watchEffect(() => {
// doubledCount.value = props.count * 2
//})
// 3. No
// value must be a reactive value, but when use pass the a primitive value to the function
// then it's not reactive, so the function will not be triggered
// useDouble(props.count) // props.count is a primitive value
//function useDouble(count) {
// const doubledCount = ref(count * 2)
// watchEffect(() => {
// doubledCount.value = count * 2
// })
// return doubledCount
//}
//const doulbedCount = useDouble(props.count)
// 4. Yes
// const doubledCount = computed(() => props.count * 2)
// 5. Yes
function useDouble(props, propName) {
const doubledCount = computed(() => props[propName] * 2)
return doubledCount
}
const doulbedCount = useDouble(props, 'count')
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-10-07 [Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)
2022-10-07 [Typescript + React] Tip: Use generics in React to make dynamic and flexible components
2022-10-07 [Typescript] 44. Medium - Drop char
2019-10-07 [Svelte 3] Use await block to wait for a promise and handle loading state in Svelte 3
2016-10-07 [TypeScript] Interface and Class