For async components in Vue.js, the resolve argument is the function which is called upon success of the async call, so your require() call needs to be inside the called resolve function. You just need to remove the brackets in your require() call and format that line as follows:
resolve(require('./components/Example2.vue'))
In the example below, we're using a basic setTimeout() to emulate the async call. The resolve function will be called after 5 seconds and will load the Example2 component into the app.
In order to show/hide the Example2 component via a button click, you have to add a reactive data property in the data() function. Then, if you take a look at App.vue's template, we're using the v-if (https://v2.vuejs.org/v2/guide/conditional.html#v-if) directive to add/remove the Example2 component to/from the virtual DOM. You could very easily us the v-show (https://v2.vuejs.org/v2/guide/conditional.html#v-show) directive here as well, although the component would stick around and just be hidden. You can read more about v-if vs v-show here: https://v2.vuejs.org/v2/guide/conditional.html#v-if-vs-v-show. This is a very common paradigm for hiding and showing modals in an app -- here's an example that shows this in action quite well: https://v2.vuejs.org/v2/examples/modal.html
main.js
import Vue from 'vue'
import App from './components/App.vue'
Vue.component('example2', function(resolve, reject) {
setTimeout(function() {
resolve(require('./components/Example2.vue'))
}, 5000)
})
const app = new Vue({
el: '#app',
render: h => h(App)
})
Example2.vue
<template>
<div>
<div>Hello example 2!</div>
</div>
</template>
App.vue
<template>
<div id="app">
<button type="button" @click="onButtonClick">Click me to add the example2 component</button>
<example2 v-if="show_example2"></example2>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
show_example2: false
}
},
methods: {
onButtonClick() {
this.show_example2: true
}
}
}
</script>