<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>