Add Vue.js to any Laravel project
Table of contents:
- Introduction to Vue.js in Laravel
- Install Vue.js in Laravel via NPM, Yarn, pnpm, or Bun
- Configure Vite for Vue.js in Laravel
- Initialize Vue.js
- Make sure Vue.js is operational
npm install vue @vitejs/plugin-vue
yarn add vue @vitejs/plugin-vue
bun add vue @vitejs/plugin-vue
import { defineConfig } from 'vite'import laravel from 'laravel-vite-plugin'import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.js'], refresh: true, }), vue(), ], resolve: { alias: { vue: 'vue/dist/vue.esm-bundler.js', }, },})
vue
to vue.esm-bundler.js
instructs Vite to use a version of Vue.js that also bundles the compiler which will allow us to write HTML instead of render()
functions (thankfully!).Inside resources/js/app.js, initialize Vue by adding the following:
import { createApp } from 'vue'const app = createApp()app.mount('#app')
- We import Vue and create a variable for the
createApp()
function. - Then, we instantiate Vue by calling the function and store it in a constant called
app
(you will see later why). - Finally, we mount our Vue.js application inside a
#app
element that we will create.
Now, do not forget to include your JavaScript using the @vite
directive and create a <div>
tag with an “app” ID in your HTML.
<!DOCTYPE html><html> <head> … @vite(['resources/js/app.js']) </head> <body> <div id="app"> <!-- Vue.js components will be processed here. --> </div> </body></html>
Make sure Vue.js is operational
Create a component called Counter in resources/js/components/Counter.vue:
<script setup> import { ref } from 'vue' const count = ref(0)</script> <template> {{ count }} <button @click="count++"> Add </button></template>
Register Counter.vue to let Vue know of its existence:
import { createApp } from 'vue'import Counter from './components/Counter.vue' const app = createApp() app.component('counter', Counter) app.mount('#app')
Then, call it in the div#app
we set up earlier:
<div id="app"> <counter /></div>
Compile your code
The only step left is to compile your code and preview the result in your browser.
If you are using NPM, run the following command:
npm run dev
If you are using Yarn:
yarn dev
Or if you are using Bun:
bun run dev
That’s all there is to it! Check your browser and it all should be working.
You’ve successfully added Vue.js to your Laravel project and you can now start having fun by building something amazing!
0 Comments
CAN FEEDBACK
Emoji