javascriptvue.jsjavascript-framework

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?


Solution

  • 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();
    }