Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass a ref to a method/function argument without unwrapping? #605

Closed
DarkLite1 opened this issue Dec 3, 2020 · 2 comments
Closed

Comments

@DarkLite1
Copy link

We're using the Vue Composition API and would like to pass a ref object, not just the value, as an argument to a function. Some code to clarify:

import { defineComponent, ref } from '@vue/composition-api'

export default defineComponent({
  setup() {
    const driverId = ref()
    const truckId = ref()

    const clearDriverId = () => {
      driverId.value = null
    }

The code above works fine, but we need to duplicate the function clearDriverId for the truckId too. That's why we would like to create something like this:

    const clearField = (field: Ref) => {
      field.value = null
    }

Accessed from the template:

<q-input
  label="Driver ID"
  v-model="driverId"
>
  <template v-slot:append>
    <q-icon
      name="close"
      @click.stop="clearField(driverId)"
    />
  </template>
</q-input>

Of course, this does not work because the ref driverId gets unwrapped when passed from the template to the function. What is the correct way to pass a complete ref object to a function?

We already asked this question on StackOverflow and in the Vue forum.

@antfu
Copy link
Member

antfu commented Dec 3, 2020

I am not very sure about this, but AFAIK, you can't get the reference in template without markRaw or some kind of hack. I'd suggest you create functions with the refs in their closure or even make a factory to do that in order to be resued.

@pikax
Copy link
Member

pikax commented Dec 3, 2020

You can send the object in a nested object, that will guarantee that the object will not be unwrapped by the template.

There's also a request to create an API for that https://github.com/vuejs/vue-next/issues/1691

We already asked this question on StackOverflow and in the Vue forum.

On the stackoverflow the answer should work.

Here's a cleaner way to do it.

export default defineComponent({
  setup() {
    const driverId = ref()
    const truckId = ref()

    const clearDriverId = () => {
      driverId.value = null
    }
   
    return {
      //driverId, // it will unwrap 
      selected: {
        driverId, // it does not unwrap
      }
  }
})

For questions please wait a bit longer before opening an issue on github, you can also ask on discord

@pikax pikax closed this as completed Dec 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants