With options API we can use these ways to extend components. Let's say we've 2 components.
Component1.vue
<script>
export default {
methods: {
init(message) {
alert(message)
}
}
}
</script>
Component2.vue
<script>
import Component1 from './Component1'
export default {
extends: Component1,
methods: {
showAlert() {
// we can access Component1 'init()' method here
this.init('Hello World!')
}
},
mounted() {
this.showAlert()
}
}
</script>
Now, how to make it work with composition API? I've checked that extends property still available at the documentation but there's no clear usage explanation about that.
https://v3.vuejs.org/api/options-composition.html#extends
Consider the following code with composition API.
Component1.vue
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup () {
const init = (message) => {
alert(message)
}
return {
init
}
}
})
</script>
Component2.vue
<script>
import { defineComponent, ref, onMounted } from 'vue'
import Component1 from './Component1.vue'
export default defineComponent({
extends: Component1,
setup () {
const showAlert = () => {
// How to access 'init()' method here?
}
onMounted(() => {
showAlert()
})
}
})
</script>
Thank you!
defineComponent. See vuejs.org/api/options-composition.html#extends a "base class" component to extend from.