Vue写项目后台02

在安装好node.js的前提下
使用cmd(管理员运行)安装vue
npm install --g vue-cli
安装好vue之后,开始初始化项目
vue init webpack music
一路回车y就可以了
此时初始化的项目有router
在music项目目录下
输入如下命令安装 element-ui组件
npm i element-ui -S
输入如下命令安装axios(axios:封装好的ajax请求)
npm install axios–save-dev
输入如下命令安装vuex
npm install vuex --save

ok~~~自此,一个vue项目vue+vuex+router+axios+element-ui就安装好了

输入如下命令安装项目依赖
npm install
输入如下命令启动项目
npm run dev

在这里插入图片描述
router目录下的index.js是路由文件,控制页面跳转
mixins目录下的Index.js是工具文件,做一些数据处理
pages目录下就是页面文件
components目录下公共页面文件
main.js是全局变量挂载的地方,引入的element-ui,router在main.js引入之后全局都可使用

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router' // 路由

import ElementUI from 'element-ui'  // element-ui文件
import 'element-ui/lib/theme-chalk/index.css'// element-ui文件


import './assets/css/main.css'  // 全局自定义css文件

Vue.config.productionTip = false


Vue.use(ElementUI)  // 使用element-ui
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,   // 路由
  components: { App },
  template: '<App/>'
})


router.index.js

import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import Login from '@/pages/Login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login // 引入上面引入的文件跳转方式
    },
    {
      path:"/Info",   // 页面切换路径
      component:resolve => require(['../pages/Info.vue'],resolve)  // 这种直接定义到页面的跳转方式
      }
  ]
})

pages.Info

<template>


  <div>
    后台首页
  </div>


</template>

<script>
</script>

<style>
</style>

pages.Login.vue

<template>
  <div id="div01">
     <div id="login-title">欢迎访问音乐网站</div>
     <div id="login-wrap">
<!-- element-ui组件 -->

<!-- :model双向数据绑定,rules验空 -->
       <el-form
       :model="loginmodel"
       :rules="rules">
       <!-- 验空提示元素 -->
       <el-form-item prop="username">
         <!-- element-ui输入文本控件 -->
         <el-input placeholder="用户名" v-model="loginmodel.username"></el-input>
       </el-form-item>

       <!-- 验空提示元素 -->
       <el-form-item prop="password">
         <!-- element-ui输入文本控件(password) -->
         <el-input placeholder="密码" v-model="loginmodel.password" type="password"></el-input>
       </el-form-item>

<!-- element-ui提交按钮 -->
<div id="login-btn"> <el-button type="primary" @click="submitFrom">登录</el-button></div>
       </el-form>

     </div>
  </div>
</template>

<script>
  import {Login }from '../api/index' // 引入Login方法axios请求
  import {mixin} from '../mixins'    // 引入mixin提示信息
  export default{
  mixins:[mixin],// 函数内部导出提示信息
data:function(){   // 数据函数
return{
loginmodel:{   // 双向数据绑定
  username:'admin',
  password:'123'
},
rules:{    // 验证规则,验空
  username:[
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}
}
},
methods:{  // @click方法
  submitFrom(){
   let params=new URLSearchParams();
   params.append('username',this.loginmodel.username)
   params.append('password',this.loginmodel.password)
   console.log(this.loginmodel.username)
   Login(params)  // 将参数传入Login()方法
   .then(res=>{
     if(res.code===1){
       this.$router.push("/Info")  // 路由跳转
       this.notify('欢迎回来','success')
     }else{
       this.notify('登录失败','error')
     }
   })
   .catch(err=>{
     console.log(err)
   })
  }
}
  }
</script>

<style>
  /* css样式 */
#div01{
  position: relative;
  background: url(../assets/img/background.jpg);
  width: 100%;
  height: 100%;
  background-size: cover;
}
#login-title{
  position: absolute;
   color: #FFFFFF;
   position: absolute;
   font-size: 30px;
   margin-top: 100px;
   margin-left: 500px;
}
#login-wrap{
  position: absolute;
  background-color: #DDDDDD;
  width: 400px;
  height: 300px;
border-radius: 10px;
margin-left: 450px;
margin-top: 150px;
padding: 20px;
}
#login-btn{
 text-align: center;
}
#login-btn button{
  width: 100%;
  height: 36px;
}
</style>

mixins.index.js

export const mixin={
  methods:{
    notify(title,type){
      this.$notify({
        title:title,
        type:type
      })
    }
  }
}

api.http.js

import axios from 'axios';
axios.defaults.timeout=5000;  // 设置请求超时时间为5秒
axios.defaults.withCredentials=true;// 设置跨域为正确
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.defaults.baseURL='http://localhost:8888'

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是2开头的的情况
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        case 401:
          router.replace({
            path: '/',
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
          break;
        case 403:
          // console.log('管理员权限已修改请重新登录')
          // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
          setTimeout(() => {
            router.replace({
              path: '/',
              query: {
                redirect: router.currentRoute.fullPath
              }
            });
          }, 1000);
          break;

        // 404请求不存在
        case 404:
          // console.log('请求页面飞到火星去了')
          break;
      }
      return Promise.reject(error.response);
    }
  });



/**
   * 封装get方法
   * @param url
   * @param data
   * @returns {Promise}
   */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
   * 封装post请求
   * @param url
   * @param data
   * @returns {Promise}
   */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

api.index.js

import {get,post} from './http'

// 登录方法
export const Login=(params)=>post(`admin/login/status`, params)

自此整个项目就差不多了
vue跨域失败,后台springboot版本有很大关系
2.4以上版本的跨域设置不一样(自行百度)
2.4以下的版本跨域设置

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 设置跨域
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值