0

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?

0

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.