<script setup>
import { ref } from 'vue'
const foo = ref(1)
function changeSth(sth, val) {
sth.val = val;
// an error trigger, because ref object is unwrapped, sth is just a plain value
}
</script>
<template>
<button @click="changeSth(foo, 2)">click me change sth.</button>
</template>
I wanna pass ref object foo into function changeSth。 so that I can reuse changeSth to do something like changeSth(foo) changeSth(bar). But now I can only get the value of ref object. So, how to pass ref object itself into event handler like changeSth with template syntax.
Try like following:
<template>
<button @click="changeSth('foo', 2)">click me change sth.</button>
{{ foo }}
</template>
<script setup>
import { ref } from 'vue'
const foo = ref(1)
function changeSth(sth, val) {
this[sth] = val
}
</script>