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?
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?
Share Improve this question asked Jan 11, 2019 at 15:43 jmona789jmona789 2,8397 gold badges26 silver badges61 bronze badges 3-
1
created
is a life cycle hook could not be invoked in that manner – Boussadjra Brahim Commented Jan 11, 2019 at 15:45 - So is there a better way to do this without duplicating the function in my methods section? – jmona789 Commented Jan 11, 2019 at 15:48
- 1 create a method call it inside created hook and call it again in your new method – Boussadjra Brahim Commented Jan 11, 2019 at 15:50
2 Answers
Reset to default 6Edited: 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();
}
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./vue@latest/dist/vue.js"></script>
<div id="app">
<button @click="$options.created">Run</button>
</div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742258690a4410500.html
评论列表(0条)