Home > Enterprise >  set emitted value in compositition Api vue 3 nuxt3
set emitted value in compositition Api vue 3 nuxt3

Time:12-13

I get the data from the component, but I don't understand how to get the data in the api composition. I can 't pass it to some variable . I can't return data from the function.

I'm new in composition api, also use nuxt.

Maybe I can use it somehow useState()

I just need to get the data in the function addToBasket

html
<SelectSize  @selectedSize="selectedSize"></SelectSize>

js

<script setup>


let selectedSize=(val)=> {

  return val
}
let addToBasket=(id)=>{
  console.log(selectedSize())
  console.log(id)
}
</script>

CodePudding user response:

You should use a ref()

const size = ref('');
const size = ref<CustomType>(); // or with types

You can set its value in selectedSize function

const selectedSize = (val) => {
    size.value = val;
}

And then you can access variable's value anywhere inside script setup. In addToBasket function for example.

const addToBasket = (id) => {
    console.log(size.value);
    console.log(id)
}

Check Vue docs for ref()

CodePudding user response:

Instead of selectedSize being a method, make it a ref: const selectedSize = ref(''). When the @selectedSize event listener fires, set the value of your selectedSize ref with the value of the $event argument that comes through to the event listener.

html
<SelectSize  @selectedSize="($event) => selectedSize = $event"></SelectSize>

js

<script setup>


let selectedSize= ref('')
let addToBasket=(id)=>{
  console.log(selectedSize.value)
  console.log(id)
}
</script>
  • Related