在 laravel 中结合 vite 搭建 vue 应用 | laravel china 社区-金年会app官方网


laravel 是一个优雅的 php web框架,在早期的版本中,一般是采用mix搭配webpack来构建前端资源。
vue 是一个渐进式 javascript 框架,vite 是下一代前端开发和构建工具。那么这个组合起来,堪称绝美

下面是我所使用的版本:

  • php 8.2
  • laravel 11.8.0
  • node 20.13
  • vite 5.0
  • vue 3.4

安装 laravel 和 vue

这里直接使用composer创建laravel项目。

composer create-project laravel/laravel example-app

接下来,在laravel项目中安装的package.json的中的默认依赖。

npm install

然后,在laravel项目中安装的vuevite插件。

npm install --save-dev vue@latest
npm install --save-dev @vitejs/plugin-vue

配置 vite

vite的配置文件是vite.config.js,修改内容如下:

import { defineconfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineconfig({
    plugins: [
        laravel(['resources/css/app.css', 'resources/js/app.js']),
        vue({
            template: {
                transformasseturls: {
                    // the vue plugin will re-write asset urls, when referenced
                    // in single file components, to point to the laravel web
                    // server. setting this to `null` allows the laravel plugin
                    // to instead re-write asset urls to point to the vite
                    // server instead.
                    base: null,
                    // the vue plugin will parse absolute urls and treat them
                    // as absolute paths to files on disk. setting this to
                    // `false` will leave absolute urls un-touched so they can
                    // reference assets in the public directory as expected.
                    includeabsolute: false,
                },
            },
        }),
    ],
});

创建vue应用并挂载组件

创建组件resources/js/components/app.vue,内容如下:

<template>
  <h1>hello laravel and vueh1>
template>

resources/js目录下的app.js文件,内容如下:

import './bootstrap';
import { createapp, ref } from 'vue'
import app from '../components/app.vue'
createapp(app).mount('#app')

引入 laravel 入口

resources/views/welcome.blade.php文件中引入:


<html lang="{{ str_replace('_', '-', app()->getlocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>laraveltitle>
        @vite('resources/css/app.css')
    head>
    <body id="app">
    body>
    @vite('resources/js/app.js')
html>

启动 laravel 和 vite 服务

laravel项目根目录下,启动laravel服务:

php artisan serve

laravel项目根目录下,启动vue服务:

npm run dev

然后,打开浏览器访问http://127.0.0.1:8000,可以看到页面效果了。

原文:

本作品采用《cc 协议》,转载必须注明作者和本文链接
从零开发一个电商项目,功能包括电商后台、商品 & sku 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
以构建论坛项目 larabbs 为线索,展开对 laravel 框架的全面学习。应用程序架构思路贴近 laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图