Home > Enterprise >  How to run Vue directive on page load?
How to run Vue directive on page load?

Time:05-16

I'm looping over an array of objects consisting of map svg paths and locales and want to run a function upon load. The function has to take the locale keys of the paths array as parameter and do something with it:

<p v-for="(country, locale) in paths" @load="myFunction(locale)">log {{locale}}</p>

but @load does nothing. The same code works with the @click directive:

<p v-for="(country, locale) in paths" @click="myFunction(locale)">log {{locale}}</p>

This is the function:

const myFunction = (locale) => {
    console.log(locale)
}

How do I make it work?

CodePudding user response:

<p v-for="(country, locale) in paths">log {{myFunction(locale)}}</p>

methods: {
    myFunction(locale) {
        // do something
    }
}

It's resolve your question?

CodePudding user response:

this sounds like directives are the wrong tools for the job. you seem to have all related variables in one array anyway, so why not iterate through the array in mounted? eg:

mounted() {
  this.paths.forEach((path) => {
    this.myFunction(path.locale);
  })
}

this could also be done in the created hook

Btw: You are not using directives here, @click and @load are just events and you register listeners to it. the element fires click on click but doesnt fire the load event, thats why it doesnt trigger your function. maybe you misunderstood what a directive is

  • Related