Write the Code. Change the World.

7月 31

前边写了一个 laravel mix vue 的基本构造使用。虽然那种结构能跑起来,可受限 laravel 自己的功能。这次,要利用 vue 的优势,elemeui 的优势,独立去构建项目。

前边一部分操作是一样的。

从零开始操作

这里以 laravel7 为例子,来使用 vue。

先安装 laravel 7

composer create-project laravel/laravel --prefer-dist testvue.cn "7.*"

cd testvue.cn

# 查看 laravel 的版本(发现是 7.22.4)
php artisan -V

# 创建 git 仓库
git init
git add .
git commit -m 'laravel 7.22.4 initialize'

浏览器访问 testvue.cn, 发现能正常访问到 laravel 基础页面(之前已经配合域名映射这些)。

安装 ui,以及依赖

composer require laravel/ui

php artisan ui vue

yarn --no-bin-links

yarn run dev

上边操作做了以下事情:

  1. 使用 composer 安装 laravel ui 软件包

  2. 生成 js/ui 文件和 package.json 修改

  3. 安装前端依赖项并编译开发环境的 js/css 文件

如果想要 laravel 自带的登录注册模板页面,可以用 php artisan ui vue --auth 替换 php artisan ui vue 命令。

:%s#cross-env ##g 批量替换 package.json 中的 cross-env 为空字符串也就是删除。

如果有 cross-env 等问题,可以参考 https://www.pilishen.com/posts/reason-and-solution-why-npm-run-dev-cannot-find-cross-env-in-laravel5.4

编写样例

# 创建一个 PageController 控制器
php artisan make:controller PageController

# 修改路由
vim routes/web.php

Route::get('/', 'PageController@index')->name('index');

修改 PageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PageController extends Controller
{
    public function index() {

        return view('index.blade.php');
    }
}

编写 resources/views/index.blade.php

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel</title>
    <link rel="stylesheet" href="{{ mix('css/app.css') }}">
</head>
<body style="margin:0;padding: 0" >
    <div id="app">

    </div>
    <script src="{{mix('/js/app.js') }}"></script>
</body>
</html>

配置 webpack.mix.js

const mix = require('laravel-mix');
let rm = require('rimraf');
/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

const publicPath = 'public/build/'

rm(publicPath, err => {
    if (err) throw err
    console.log("清空编译文件夹\n\n")
});

mix.js('resources/assets/js/app.js', `${publicPath}js/`).extract(['vue'])
    .sass('resources/assets/sass/app.scss', `${publicPath}css/`);

if (mix.inProduction()) {
    mix.version();
    mix.webpackConfig({
        output: {
            chunkFilename: 'build/[id].[hash].js'
        }
    });
} else {
    mix.webpackConfig({
        output: {
            chunkFilename: 'build/[id].js'
        }
    });
}

在 resources 目录下,新建 assets 目录,这里放 vue 项目的文件。

resources/assets/js/app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

window.Vue = require('vue');

import App from './app.vue';
import ElementUI from 'element-ui';
import router from './router/';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

const app = new Vue({
    el: '#app',
    router,
    render: h => h(App)
});

resources/assets/js/app.vue

<template>
  <div>
    <el-container v-if="isLogin">
      <router-view></router-view>
    </el-container>
  </div>
</template>

<script>


export default {
  name: "app",
  data() {
    return {
      isLogin: true,
      userInfo: {},
    };
  },
  mounted() {
  },
  watch: {
    $route: function (route) {
      if (!this.isLogin) {
        return;
      }
      this.isLanding = false;
      this.routeChange(route.path);
    },
  },
  methods: {
    routeChange(path) {

    }
  },
};
</script>

<style lang="scss">

</style>

resources/assets/js/router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import admin from '../router/admin.js'

Vue.use(VueRouter);

let vueRoutes = {
    saveScrollPosition: true,
    routes: [
        {
            name: 'welcome',
            path: '/',
            component: resolve => void(require(['../views/welcome.vue'], resolve))
        }
    ]
};

vueRoutes.routes = vueRoutes.routes.concat(admin);

export default new VueRouter(vueRoutes);

resources/assets/js/router/admin.js

export default [
    {
        name: 'login',
        path: '/admin/user/login',
        component: resolve => void (require(['../views/user/login.vue'], resolve))
    },
    {
        name: 'register',
        path: '/admin/user/register',
        component: resolve => void (require(['../views/user/register.vue'], resolve))
    }
]

resources/assets/js/views/welcome.vue

<template>
    <div>
        <h1>Hello, Laravel</h1>
    </div>
</template>

<script>
    export default {
        data() {
            return {

            }
        },
        methods: {

        }
    }
</script>

resources/assets/js/views/user/login.vue
resources/assets/js/views/user/register.vue

<template>
  <div class="login-panel">
    <el-row class="login-form">
      <el-alert :title="error" type="error" v-if="error"></el-alert>
      <el-form
        label-position="top"
        label-width="80px"
        :model="formData"
        ref="form"
        :rules="formRule"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" autocomplete="on" name="username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            autocomplete="on"
            name="password"
            @keyup.enter.native="login('form')"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login('form')" size="samll">登录</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      error: "",
      formData: {
        username: "",
        password: "",
      },
      formRule: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {},
  methods: {
    login() {},
  },
};
</script>

<style lang="scss" scoped>
.login-panel {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;

  .login-form {
    background-color: #f9f9f9;
    width: 350px;
    margin-left: auto;
    margin-right: auto;
    padding: 30px;
    margin-top: 10px;
    -webkit-box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08), 0 9px 28px 0 rgba(0, 0, 0, 0.05), 0 12px 48px 16px rgba(0, 0, 0, 0.03);
    box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08), 0 9px 28px 0 rgba(0, 0, 0, 0.05), 0 12px 48px 16px rgba(0, 0, 0, 0.03);
  }
}
</style>

assets/sass/app.scss

html {
    margin: 0;
    padding: 0;
}

到这里,只是用到了 elemeui 和路由来一起构建项目。下一步使用 https://panjiachen.github.io/vue-element-admin-site/zh/ 来构建更加强大的后台。

http://www.javanx.cn/20190318/vue-elementui-admin/

发表评论

电子邮件地址不会被公开。 必填项已用*标注