'Extend component with composition API in Vue.js
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!
Solution 1:[1]
Late to the party but check this:
https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md#global-api-mapping
export default defineComponent({ extends: defineComponent({ ... }) });
Also this https://github.com/pearofducks/mount-vue-component
Solution 2:[2]
Composition api enforces the code reusability with composable function which could be used across multiple components, so create a file named useInit.js with following content :
const useInit=()=>{
const init = (message) => {
alert(message)
}
return {
init
}
}
export default useInit;
then import it in every component like:
component 1
<script>
import { defineComponent, ref } from 'vue'
import useInit from './useInit'
export default defineComponent({
setup () {
const {init} = useInit()
return {
init
}
}
})
</script>
Component 2
<script>
import { defineComponent, ref, onMounted } from 'vue'
import Component1 from './Component1.vue'
import useInit from './useInit'
export default defineComponent({
setup () {
const {init} = useInit()
const showAlert = () => {
init()
}
onMounted(() => {
showAlert()
})
}
})
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wobsoriano |
| Solution 2 |
