I’m using Quasar with Vue 3 and having trouble passing variables from one component to another. I’ve tried using provide
/inject
and props in the script setup
mode, as well as export
in the script
mode, but whichever method I use, I get undefined
or unknown
when trying to print the received item to the console.
Here is a simple example:
// Parent component
<script setup lang="ts">
import { provide } from 'vue'
const nums = [1, 2]
provide(nums, 'numbers')
</script>
// Child component
<script setup lang="ts">
const numbers = inject('nums')
console.log(numbers) // prints undefined or unknown
</script>
// Parent component
<script setup lang="ts">
const nums = [1, 2]
</script>
// Child component
<script setup lang="ts">
import parent from './parent.vue'
import { PropType } from 'vue'
const props = defineProps({
numbers: {
type: Array as () => number[],
required: true
})
console.log(props.nums) // prints undefined or unknown
What am I doing wrong?
In the first example, you are using the wrong key when providing the value. Instead of provide(nums, 'numbers')
, it should be provide('numbers', nums)
.
Here is the corrected code:
<!-- Parent component -->
<script setup lang="ts">
import { provide } from 'vue'
const nums = [1, 2]
provide('numbers', nums)
</script>
<!-- Child component -->
<script setup lang="ts">
import { inject } from 'vue'
const numbers = inject('numbers')
console.log(numbers) // prints [1, 2]
</script>
In the second example, you are using the wrong prop name when logging the value. Instead of console.log(props.nums)
, it should be console.log(props.numbers)
.
Here is the corrected code:
<!-- Parent component -->
<script setup lang="ts">
const nums = [1, 2]
</script>
<!-- Child component -->
<script setup lang="ts">
import { defineProps } from 'vue'
const props = defineProps({
numbers: {
type: Array as PropType<number[]>,
required: true
}
})
console.log(props.numbers) // prints [1, 2]
</script>
Make sure to use the correct key or prop name when providing and injecting the value.