tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file?
I incorporate Vue to improve user interactions on specific pages like the registration page. This involves handling ajax requests and displaying server errors without refreshing the entire page, creating mini single-page applications within a multi-page application...
In Vue2, importing Vue in the base file and utilizing Vue's options API in other files worked smoothly. The subsequent files remained concise as they only included logic relevant to that particular file.
However, with Vue3's composition API requiring imports such as
ref, reactive, watch, onMount...etc
, this leads to repetitive imports of Vue in the subsequent files. I tried to tackle this issue with the following approach:
// register.blade.php (excerpt)
<div id="root">
<input type="text" name="first_name" v-model="FirstName">
<input type="text" name="last_name" v-model="LastName">
// (before edit) <script src="main.js"></script>
// (before edit) <script src="register.js"></script>
<script src="{{ mix('/main.js') }}"></script>
<script src="{{ mix('/register.js') }}"></script>
</div>
// main.js (excerpt)
// (before edit) import Vue from 'node_modules/vue/dist/vue.js';
// (before edit) window.Vue = Vue;
window.Vue = require('vue');
// register.js (excerpt)
const app = Vue.createApp({
setup() {
const FirstName = Vue.ref('');
const LastName = Vue.ref('');
const FullName = Vue.computed(() => FirstName.value + ' ' + LastName.value);
return {
FirstName, LastName, FullName
}
}
});
app.mount('#root');
This method works well for this simple example, but I am unsure if using Vue.
prefix is correct. Is it acceptable to access all the exposed functions by Vue in the setup() method using this syntax?
EDIT: I employ webpack with laravel mix. Although I omitted these details initially, they are essential. Comments indicate edits made to the initial code to prevent confusion.
// webpack.mix.js (excerpt)
mix.webpackConfig({
resolve: {
alias: {
'vue$': path.resolve(__dirname, 'node_modules/vue/dist/vue.esm-bundler.js'),
}
}
});
mix.js('resources/main.js', 'public/main.js')
.js('resources/register.js', 'public/register.js')
.version();