Reputation: 21
I have a vue-cli project. It means, I have 1 .vue file and main.js. I want to call method from .vue file in main.js But I get error that function is not defined. How can I call inside .vue file method in main.js? Method should be defined in .vue file NOT in main.js in new Vue{}.
Upvotes: 2
Views: 4231
Reputation: 3615
I don't believe you can do it exactly the way you are asking as the .vue component is child of the parent instance defined in the main.js file and is out of scope. What you can do is define the function or functions you want to use in this way as a mix-in.
Create a separate js file to define your mixin like follows
var myMixin = {
data: function () {
return {
//
},
methods:{
myAwesomeMethod(){...}
}
}
Then import it in your main js like so:
import myMixin from '/mixins/myMixin.js';
Then reference it in your Vue instance
new Vue({
mixins: [myMixin],
})
After than you can call the method in your main.js using this.myAwesomeMethod
Alternatively you can define your mixin like follows and only import it with no need to reference it.
Vue.mixin({
methods:{
myAwesomeMethod(){
//...
}
}
});
I don't recommend it, however, if you absolutely cant make any modification to the main.js file, then you could simply define your mixin using the latter method directly in your .vue file outside of the definition for your component.
<script>
// define your mixin
Vue.mixin({
methods:{
myAwesomeMethod(){
//..
}
}
});
// define your component
export default {
data: function () {
return {
}
}
}
</script>
Then the mixin should be available to be called anywhere.
Upvotes: 1