简体   繁体   中英

run method in Vue-Js only once

I want to add random number (from 0 to price of item) to one of data properties in vue js but only once when page is loaded, but i cant use mounted and computed because i wanna send parameter to the function... i tried this way but its not work (this function run with every change on the page, and every time give me another random number)..

its my code

{{getRandomNumber(item)}}
data(){
   return {
     getRandomNum = true,
     moneyOfSellItems = 0,
   }
},
methods: {
 getRandomNumber(item) {
  if (this.getRandomNum) {
   this.moneyOfSellItems = Math.floor(Math.random() * `${item.price}`) + 2;
   return this.moneyOfSellItems;
   this.getRandomNum = false;
  }
 }
}

Every time your component will re-render, the number will change. And with your method (having a boolean to set to false to prevent re-render), the number will show the fist time and the other times, nothing will show at all because when this.getRandomNum is false, then getRandomNumber() doesn't return anything. In your specific case, it will keep returning a different number because your line

this.getRandomNum = false;

will never run as it's after a return statement;

I suggest having a randomNum in your data set to null and have getRandomNumber() return that number if it's set or set it to a random number

data(){
   return {
     randomNum: null
   }
},
methods: {
 getRandomNumber(item) {
  if (this.randomNum === null) {
   this.randomNum = Math.floor(Math.random() * `${item.price}`) + 2;
  }
  return this.randomNum;
 }
}

have you tried to call your function inside mounted function? I mean, something like this:

mounted(){
 this.getRandomNumber(item);
}

Hope this could help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM