I have a component in which I define a reactive variable, and I would like to use it in an imported function. A simple example of the code is available in the playground
App.vue
<script setup>
import { change } from './lib.js'
import { ref } from 'vue'
const msg = ref('one')
change()
</script>
<template>
<h1>{{ msg }}</h1>
</template>
lib.js
export const change = () => msg.value = 'two'
The code above of course does not work because change()
does not know msg
. Msg
on the other hand is not exportable as a <setup script>
only variable.
My question: how should I declare msg
so that I can refer to it from that exported function? Or, alternatively, is it possible to declare a reactive variable in lib.js
?
CodePudding user response:
You could pass the msg
as a param to your change
method like this
lib.js
export const change = (msg) => msg.value = 'two'
and use it like that in your file
App.vue
const msg = ref('one')
change(msg)