Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue can you call the created() function from a method?

So I'm making an app in vue, on page load it takes a cookie with the user's zip and performs a search using that zip, but the user is also allowed to change that zip if its wrong so I want to be able to call the created method from inside a regular method that will run when they change the zip, is that possible in Vue?

like image 644
jmona789 Avatar asked Oct 20 '25 19:10

jmona789


2 Answers

Edited: I thought it's not possible but as @RoyJ pointed, apparently, you can but below is the alternative solution instead of invoking the created() hook.

What you can do instead is define another function under your methods property which you can call during the created hook and when there's a change to zip then you can call the same function.

In this way, you define the logic only in one place and just reuse it when you need it.

methods: {
  zipCodeRelatedRequest() {
    // core logic here
  },
  handleZipChange() {
    this.zipCodeRelatedRequest()
  }
},
created() {
  this.zipCodeRelatedRequest();
}

like image 192
Ana Liza Pandac Avatar answered Oct 23 '25 08:10

Ana Liza Pandac


It is possible using $options. But as Ana pointed out, you should be defining a method that created calls. Calling created confuses its purpose. The other method should be named in a way that makes its purpose clear.

Example using $options, just to demonstrate possibility:

new Vue({
  el: '#app',
  created() {
    console.log("Created");
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <button @click="$options.created">Run</button>
</div>
like image 27
Roy J Avatar answered Oct 23 '25 08:10

Roy J