Vincent Dilly
Vincent Dilly

Reputation: 31

VUE/NUXT: Pass random number as props to child component

I want to have a randomNumber variable inside a vue component. But in my template and in my script tag, the values never match.

using datas:

<template>
 <div :data-number="randomNumber"
</template>
<script>
export default {
 data (){
  return { randomNumber: Math.random() * 1000}
 },
 mounted: function(){
  console.log(this.randomNumber)
 }
}
</script>

using computed property:

<template>
 <div :data-number="randomNumber"
</template>
<script>
export default {
 computed{
  randomNumber: Math.random() * 1000
 },
 mounted: function(){
  console.log(this.randomNumber)
 }
}
</script>

Or passing the randomNumber as props from my parent component.

I expect data-number to be equal to this.randomNumber, but it's never the case.

I managed to get a workaround for my project, but I'm still interested in the solution here.

Any help will be much appreciated, thanks !

Upvotes: 1

Views: 1851

Answers (1)

onuriltan
onuriltan

Reputation: 3898

The problem is that you need to first initialize randomNumber variable number as null, then assign a value in the mounted() method like:

Main Component

<template>
  <div id="app">
    {{randomNumber}}
   <ChildComp :randomNum="randomNumber"/>
  </div>
</template>

<script>
import ChildComp from './components/ChildComp'
export default {
  name: "App",
  data (){
    return { 
      randomNumber: null
    }
 },
 mounted: function(){
  this.randomNumber = Math.random() * 1000
 },
 components: {
   ChildComp
 }
};
</script>

Child Component

<template>
  <div>{{randomNum}}</div>
</template>

<script>
export default {
  name: "ChildComp",
  props: {
    randomNum: Number
  }
};
</script>

This gives the same output every time like

190.9193234159494
190.9193234159494

Because you don't know how many times your data or computed functions trigger and initialize the variable.

Upvotes: 1

Related Questions