1.Vue2使用ElementUI-初识及环境搭建

目录

一.环境准备

1.下载nodejs v16.x

2.设置淘宝镜像源

3.安装脚手架

二.Vue项目

1.创建一个项目

2.项目修改

三.Vue使用Element-UI

1.安装Element-UI

2.引入Element-UI 

四.Vue封装前后端数据交互工具

1.安装 axios

2.封装request.js

五.使用particles动态粒子效果,优化登录页


代码地址:easy-paas: EasyPass平台

一.环境准备

1.下载nodejs v16.x

下载地址:Node.js — Download Node.js®

2.设置淘宝镜像源

# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com/

# 查看
vue config
Resolved path: C:\Users\oslee\.vuerc
 {
  "useTaobaoRegistry": false
}

3.安装脚手架

vue2.x语法参考官网(后续更新3.x教程):介绍 — Vue.js

安装 | Vue CLI

npm install -g @vue/cli

# 可以用这个命令来检查其版本是否正确
vue --version

可能发生的问题

vue : 无法加载文件 C:\Users\XXX\AppData\Roaming\npm\vue.ps1,因为在此系统上禁止运行脚本

解决: 搜索powershell,以管理员的身份运行 输入下面的指令:set-ExecutionPolicy RemoteSigned 选择y

二.Vue项目

1.创建一个项目

创建一个项目 | Vue CLI

vue create vue

 

​ ​ 

# 启动
cd vue
npm run serve

2.项目修改

# 修改vue/vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  devServer: {
    port: 7000
  },
  chainWebpack: config => {
    config.plugin('html')
        .tap(args=> {
          args[0].title = "oslee好帅"
          return args
        })
  }
})
# vue/src/App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>
# vue/src/views/HomeView.vue

<template>
  <div>
    主页
  </div>
</template>

<script>
export default {
  name: 'HomeView',
}
</script>
# vue/src/router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import(/* webpackChunkName: "about" */ '../views/HomeView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
# vue/src/assets/css/global.css

* {
    box-sizing: border-box;
}
body{
    color: #333;
    font-size: 14px;
    margin: 0;
    padding: 0;
}

三.Vue使用Element-UI

1.安装Element-UI

Element-UI网址:Element - The world's most popular Vue UI framework

# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com/

# 查看npm镜像
npm config get

# 也可安装nrm管理npm镜像
npm install nrm -g

# 切换镜像并查看
nrm ls
nrm use taobao
nrm current

# 安装element-ui
npm i element-ui -S

2.引入Element-UI 

在main.js中写入以下内容:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import '@/assets/css/global.css'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI, {size:'small'});

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

四.Vue封装前后端数据交互工具

1.安装 axios

npm i axios -S

2.封装request.js

import axios from 'axios'

// 创建可一个新的axios对象
const request = axios.create({
    baseURL: 'http://localhost:9090',   // 后端的接口地址  ip:port
    timeout: 30000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    // let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
    // config.headers['token'] = 'token'  // 设置请求头

    return config
}, error => {
    console.error('request error: ' + error) // for debug
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;

        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        console.error('response error: ' + error) // for debug
        return Promise.reject(error)
    }
)


export default request

五.使用particles动态粒子效果,优化登录页

1.引入插件

npm install vue-particles --save-dev
// main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import '@/assets/css/global.css'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import VueParticles from 'vue-particles'
Vue.use(VueParticles)

Vue.use(ElementUI, {size:'small'});

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
#src/views/Login.vue

<template>
  <div  class="login-wrap">
  <div style="display: flex; background-color: #f5efef; width: 50%; height:50%; border-radius: 5px; overflow: hidden">
    <div style="flex: 1">
      <img src="@/assets/login.png" alt="" style="width: 100%; height:100%">
    </div>
    <div style="flex: 1; display: flex; align-items: center; justify-content: center">
      <el-form :model="loginForm" style="width: 80%" :rules="rules" ref="loginForm">
        <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">欢迎登录EasyPaas平台</div>
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入密码" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-form-item>
            <SliderVerify ref="verify"></SliderVerify>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="submitLogin">登 录</el-button>
        </el-form-item>
        <div style="display: flex">
          <div style="flex: 1">还没有账号?请 <span style="color: #0f9876; cursor: pointer" @click="$router.push('/register')">注册</span></div>
          <div style="flex: 1; text-align: right"><span style="color: #000000; cursor: pointer">忘记密码</span></div>
        </div>
      </el-form>
    </div>

    <div class="particles">
      <vue-particles
          color="#dedede"
          shapeType="star"
          linesColor="#dedede"
          hoverMode="grab"
          clickMode="push"
          style="height: 100%"
      ></vue-particles>
    </div>
  </div>
  </div>
</template>

<script>
import SliderVerify from "@/components/SliderVerify.vue";
import request from "@/utils/request";
export default {
  name: "Login",
  components: { SliderVerify },
  data() {
    return {
      captchaUrl: "",
      loginForm: {
        username: "",
        password: "",
      },
      checked: true,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 14,
            message: "长度在 5 到 14 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          ,
          { min: 4, message: "密码长度要大于4", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitLogin() {
      if (this.$refs.verify) {
        if (!this.$refs.verify.confirmSuccess) {
          this.$message.error("请拖动滑块验证");
          return;
        }
      }
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          request.post('/admin_login/login', this.loginForm).then(res => {
            if (res.errno == '0') {
              this.$router.push('/')
              this.$message.success('登录成功')
              localStorage.setItem("paas-user", JSON.stringify(res.data))  // 存储用户数据
            } else {
              this.$message.error(res.errmsg)
              console.log(res)
            }
          })
        } else {
          this.$message.error("登录出错请重新输入");
          return false;
        }
      });
    },
  },
};
</script>


<style scoped>
.login-wrap {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.particles {
  position: absolute;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100%;
  z-index: -1;
  background: radial-gradient(ellipse at top left, #3d2579 0%, #7370e3 57%);
}
.loginContainer {
  border-radius: 16px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 40px;
  background: aliceblue;
  border: 1px solid rgb(255, 255, 255);
  box-shadow: 0 0 25px #dad9db;
}
.loginTitle {
  margin: 0px auto 30px auto;
  text-align: center;
  font-size: 40px;
  color: #000c17;
}
.loginRemember {
  text-align: left;
  margin: 0px 0px 15px 0px;
}

</style>

# src/components/SliderVerify.vue

<template>
  <div class="drag" ref="dragDiv">
    <div class="drag_bg"></div>
    <div class="drag_text">{{ confirmWords }}</div>
    <div
      ref="moveDiv"
      @mousedown="mouseDownFn($event)"
      :class="{ handler_ok_bg: confirmSuccess }"
      class="handler handler_bg"
      style="position: absolute; top: 0px; left: 0px"
    ></div>
  </div>
</template>

<script>
export default {
  name: "SliderVerify",
  data() {
    return {
      beginClientX: 0 /*距离屏幕左端距离*/,
      mouseMoveState: false /*触发拖动状态  判断*/,
      maxWidth: "" /*拖动最大宽度,依据滑块宽度算出来的*/,
      confirmWords: "向右拖动滑块验证" /*滑块文字*/,
      confirmSuccess: false /*验证成功判断*/,
    };
  },
  methods: {
    //mousedown 事件
    mouseDownFn: function (e) {
        console.log('mouseDownFn' + e.clientX)
      if (!this.confirmSuccess) {
        e.preventDefault && e.preventDefault(); //阻止文字选中等 浏览器默认事件
        this.mouseMoveState = true;
        this.beginClientX = e.clientX;
      }
    },
    //验证成功函数
    successFunction() {
      this.confirmSuccess = true;
      this.confirmWords = "验证通过";
      if (window.addEventListener) {
        document
          .getElementsByTagName("html")[0]
          .removeEventListener("mousemove", this.mouseMoveFn);
        document
          .getElementsByTagName("html")[0]
          .removeEventListener("mouseup", this.moseUpFn);
      } else {
        document
          .getElementsByTagName("html")[0]
          .removeEventListener("mouseup", () => {});
      }
      document.getElementsByClassName("drag_text")[0].style.color = "#fff";
      document.getElementsByClassName("handler")[0].style.left =
        this.maxWidth + "px";
      document.getElementsByClassName("drag_bg")[0].style.width =
        this.maxWidth + "px";
    },
    //mousemove事件
    mouseMoveFn(e) {
      if (this.mouseMoveState) {
        let width = e.clientX - this.beginClientX;
        if (width > 0 && width <= this.maxWidth) {
          document.getElementsByClassName("handler")[0].style.left =
            width + "px";
          document.getElementsByClassName("drag_bg")[0].style.width =
            width + "px";
        } else if (width > this.maxWidth) {
          this.successFunction();
        }
      }
    },
    //mouseup事件
    moseUpFn(e) {
        console.log('moseUpFn' + e.clientX)
      this.mouseMoveState = false;
      var width = e.clientX - this.beginClientX;
      if (width < this.maxWidth) {
        document.getElementsByClassName("handler")[0].style.left = 0 + "px";
        document.getElementsByClassName("drag_bg")[0].style.width = 0 + "px";
      }
    },
  },
  mounted() {
    this.maxWidth =
      this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
    document
      .getElementsByTagName("html")[0]
      .addEventListener("mousemove", this.mouseMoveFn);
    document
      .getElementsByTagName("html")[0]
      .addEventListener("mouseup", this.moseUpFn);
  },
};
</script>
<style scoped>
.drag {
  position: relative;
  background-color: #e8e8e8;
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 4px;
}
.handler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DIDIwMTQgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo2MTc5NzNmZS02OTQxLTQyOTYtYTIwNi02NDI2YTNkOWU5YmUiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NGQ4ZTVmOTMtOTZiNC00ZTVkLThhY2ItN2U2ODhmMjE1NmU2Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+YiRG4AAAALFJREFUeNpi/P//PwMlgImBQkA9A+bOnfsIiBOxKcInh+yCaCDuByoswaIOpxwjciACFegBqZ1AvBSIS5OTk/8TkmNEjwWgQiUgtQuIjwAxUF3yX3xyGIEIFLwHpKyAWB+I1xGSwxULIGf9A7mQkBwTlhBXAFLHgPgqEAcTkmNCU6AL9d8WII4HOvk3ITkWJAXWUMlOoGQHmsE45ViQ2KuBuASoYC4Wf+OUYxz6mQkgwAAN9mIrUReCXgAAAABJRU5ErkJggg==")
    no-repeat center;
}
.handler_ok_bg {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  background: #fff
    url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZ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J78AEDTBiwGYg5gbifCSxFCZoaBMCy4A4GOjnH0D6DpK4IxNSVIHAfSDOAeLraJrjgJp/AwPbHMhejiQnwYRmUzNQ4VQgDQqXK0ia/0I17wJiPmQNTNBEAgMlQIWiQA2vgWw7QppBekGxsAjIiEUSBNnsBDWEAY9mEFgMMgBk00E0iZtA7AHEctDQ58MRuA6wlLgGFMoMpIG1QFeGwAIxGZo8GUhIysmwQGSAZgwHaEZhICIzOaBkJkqyM0CAAQDGx279Jf50AAAAAABJRU5ErkJggg==")
    no-repeat center;
}
.drag_bg {
  background-color: #7ac23c;
  height: 40px;
  width: 0px;
  border-radius: 4px 0px 0px 4px;
}
.drag_text {
  position: absolute;
  top: 0px;
  width: 100%;
  text-align: center;
  -moz-user-select: none;
  -webkit-user-select: none;
  user-select: none;
  -o-user-select: none;
  -ms-user-select: none;
}
</style>

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值