Reputation:
to switch from one component to another component , I use <component>
element from vue which is used to render the components dynamically by adding :is special attribute. <component :is="selected"></component>
my code :
<template>
<div>
<component :is="selected"></component>
<b-button @click="nextComponent">next</b-button>
</div>
</template>
there are two new components called Home and Contact inside our components folder.
<script>
import Home from "./components/Home";
import Contact from "./components/Contact";
export default {
data: function() {
return {
tabs: ["Home", "Contact"],
selected: "Home"
};
},
components: {
Home,
Contact
},
nextComponent () {
let index = 0
let nameComponent = this.tabs[index]
const total = this.tabs.length
if (index >= total) {
index = 0
this.selected = nameComponent
} else {
index++
this.selected = nameComponent
}
this.$emit('save')
}
};
</script>
the issue is how to call the function save
of active component . I mean if ie selected = Home
how to call save
in Home.Vue ?
There are these functions in my components
mounted () {
this.$on('save', this.save)
},
methods: {
save () {
console.log('to check if it works')
}
}
but it doesn't works
Upvotes: 0
Views: 142
Reputation: 2889
When you do this, you are only registering the save
function to be triggered on the 'save' event. You are not executing/calling the function in mounted
hook.
mounted () {
this.$on('save', this.save)
},
To call it on the initial mount, just execute the function in mounted
too.
Like so:
mounted () {
this.$on('save', this.save);
this.save() // <-- calling the function when component mounts
},
Now this function save
will be called on initial mount and whenever it gets the 'save' event.
Upvotes: 1