简体   繁体   中英

Run function when element was created

I have some elements created by v-for. How can I run the function only once by keeping 'for every element creation' as a condition .

<div v-for"value in values">
   <div @ function(value, domElement) if value.bool===true @>
              </div>

the easiest way, IMO, would be to make each of those elements a Vue Component & pass the function down as a prop.

File One

<div v-for="value in values">
   <Custom-Component :propValue="value" :propFunction="functionYouNeed" />
</div>

Custom Component

<template>
  <div> {{propValue.value}} </div>
</template>

<script>
 export default {
   props: ['propFunction', 'propValue'],
   created(){
      if (this.propValue.bool === true) { 
         this.propFunction()
      }
   }
 }
</script>

It's not so clear what exactly you want:

<div @ function(value, domElement) if value.bool===true @>

So, here's all possible solutions you want to implement.

You can bind the method usingonce modifier:

<div @click.once="yourMethod">

Or, if you want not to change the content then you can use v-once :

<div v-once>{{ neverChanged }}</div>

But if you just need to use the function when it was created then call the function inside created property and do not bind the method anywhere else.

created() {
  if(condition) {
    this.yourMethod()
  }
}

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