• 周五. 3月 29th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Vue

admin

11月 28, 2021

VUE

介绍 — Vue.js (vuejs.org)

v-bind绑定

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--  导入vue.js  -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>
<body>
<!--view层 模板-->
<div id="app">
    <span v-bind:title="message">
        鼠标停悬几秒查看此处动态绑定的提示信息~
    </span>

</div>
<script>
    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
            message:"hello,vue!"
        }
    });
</script>
</body>
</html>

v-if/v-else-if/v-else

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<!--view层 模板-->
<div id="app">

  <h1 v-if = "type==='A'">AAA</h1>
  <h1 v-else-if = "type==='B'">BBB</h1>
  <h1 v-else-if = "type==='C'">CCC</h1>
  <h1 v-else>dddd</h1>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
            type: "A"
        }
    });
</script>
</body>
</html>

v-for

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<!--view层 模板-->
<div id="app">
  <li v-for="(item,index) in items">
    {{item.message}}---{{index}}
  </li>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
            items: [
              {message: "123"},
              {message: "345"}
            ]
        }
    });
</script>
</body>
</html>

v-on/Vue.methods

  • 方法必须定义在vue的Method对象中 v-on:事件
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<!--view层 模板-->
<div id="app">
  <button v-on:click="sayHi">sayHi</button>
    <br>
  <button v-on:click="smile">smile</button>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
          message: "Summer"
        },
        methods: {//方法必须定义在vue的Method对象中 v-on:事件
          sayHi: function(a){
            alert(this.message)
          },
          smile: function(a){
            alert(this.message)
          }
        }
    });
</script>
</body>
</html>

v-model

  • 表单双向绑定:v-model指令在表单input tesxarea select 元素上双向绑定
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

<div id="app">
    <textarea name="" id="" cols="30" rows="10" v-model="message"></textarea>
    {{message}}
    <br>
    性别:
    <input type="radio" name="sex" value="男" v-model="check">男
    <input type="radio" name="sex" value="女" v-model="check">女
    <p>
        选中了:{{check}}
    </p>
    <br>
    下拉框:
    <select v-model="select">
        <option value="" disabled>--请选择--</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
        <option>D</option>
    </select>
    value:{{select}}
</div>
<script>
    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
          message: "Summer",
          check:"",
          select:""
        },
        methods: {//方法必须定义在vue的Method对象中 v-on:事件
          sayHi: function(a){
            alert(this.message)
          },
          smile: function(a){
            alert(this.message)
          }
        }
    });

</script>
</body>
</html>

定义VUE组件

  • 定义标签
  • 用Vue.component 一个组件名一个对象
    • 定义组件名
    • 对象中用props绑定参数 template定义模板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<!--view层 模板-->
<div id="app">
<!--    组件:传递给组件中的值:props-->
    <summer v-for="item in items" v-bind:bang="item"></summer>
</div>
<script>
//定义一个vue组件
    Vue.component("summer",{
        props:['bang'],
        template: '<li>{{bang}}</li>'
    });

    var vm = new Vue({
        el:"#app",
        // Model层
        data:{
          items: ["Summer","Spring"]
        }
    });
</script>
</body>
</html>

Axios异步通信

通信一般想到JQuery,但是JQuery操作DOM太频繁,不推荐用

分类:鼠标事件 | jQuery API中文文档(适用jQuery 1.0 – jQuery 3.3.1) (html.cn)



  • 钩子函数 链式函数 ES6新特性

data.json

{
  "message": "hello,vue!",
  "links": [
    "a",
    "b"
  ],
  "url": "https://www.baidu.com"
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--v-clock解决闪烁问题  display: none; 没加载前白屏-->
    <style>
       [v-clock]{
           display: none;
       }
    </style>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--view层 模板-->
<div id="app" v-clock>
    <div>{{info.message}}</div>
    <div>{{info.links}}</div>
    <a v-bind:href="info.url">点我</a>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        //data:{}, vue的data属性
        data(){
            return{//return的是一个格式
                //请求的返回参数合适,必须和json字符串一样
                info:{
                    message:null,
                    url:null,
                    links:[]
                }
            }
        },
        mounted() {    //钩子函数 链式函数 ES6新特性
            //jQuery和Ajax都可以在这里处理 但是要处理dom
            //axios 用到 data(){return{}}格式即可绑定
            axios.get('../data.json').then(response => (this.info=response.data));
        }
    });
</script>
</body>
</html>

计算属性computed

  • 内存中运行:虚拟Dom(相当于缓存)
  • 计算属性的主要特性就是为了将不经常变化的计算结果进行缓存,以节约我们的系统开销
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
    <!--    调用方法必须要加括号哦-->
    <p>currentTime1:{{currentTime1()}}</p>
    <p>currentTime2:{{currentTime2}}</p>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            message: "summer"
        },
        //计算属性的主要特性就是为了将不经常变化的计算结果进行缓存,以节约我们的系统开销
        computed: {//计算属性 methods与computed重名之后会 优先右methods
            currentTime2: function () {
                this.message;
                return Date.now();//返回当前时间戳
            }
        },
        methods: {
            currentTime1: function () {
                return Date.now();//返回当前时间戳
            }
        }
    });
</script>
</body>
</html>

内容分发slot插槽

  • 在VUE中我们使用元素作为承载分发内容的出口,作者插槽,可以应用在组合组件的场景中
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
    <todo>
        <todo-title slot="todo-title" :title="title"></todo-title>
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items>
    </todo>
</div>
<script>
    //<slot>插槽
    Vue.component("todo", {
        template:
            '<div>
                <slot name="todo-title"></slot>
                <ul>
                   <slot name="todo-items"></slot>
                </ul>
            </div>'
    });
    Vue.component("todo-title", {
        props:["title"],
        template: '<div>{{title}}</div>>'
    });
    Vue.component("todo-items", {
        props:["item"],
        template: '<li>{{item}}</li>>'
    });
    var vm = new Vue({
        el: "#app",
        data:{
            title:"HA",
            todoItems:["spring","summer","fall","winter"]
        }
    });
</script>
</body>
</html>

自定义事件this.$emit

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--  导入vue.js  -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
    <todo>
        <todo-title slot="todo-title" :title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>
</div>
<script>
    //<slot>插槽
    Vue.component("todo", {
        template:
            '<div>
                <slot name="todo-title"></slot>
                <ul>
                   <slot name="todo-items"></slot>
                </ul>
            </div>'
    });
    Vue.component("todo-title", {
        props: ["title"],
        template: '<div>{{title}}</div>'
    });
    Vue.component("todo-items", {
        props: ["item","index"],
        //只能绑定当前组件的方法
        template: '<li>{{index}}----{{item}} <button v-on:click="remove">删除</button> </li>',
        methods: {
            remove: function (index) {
                //this.$emit 自定义事件分发
                this.$emit("remove",index);
            }
        }
    });
    var vm = new Vue({
        el: "#app",
        data: {
            title: "HA",
            todoItems: ["spring", "summer", "fall", "winter"]
        },
        methods: {
            removeItems: function (index) {
                console.log("删除了"+this.todoItems.index+" OK~");
                this.todoItems.splice(index,1);//一次删除一个元素
            }
        }
    });
</script>
</body>
</html>

Vue入门小结

  • 核心:数据驱动,组件化

    优点:借鉴了AngulaJS的模块化开发和React的虚拟Dom,虚拟Dom就是把Dom操作放到内存中执行

  • 常用的属性

    • v-if
    • v-else-if
    • v-else
    • v-for
    • v-on 绑定事件,简写@
    • v-model 数据双向绑定
    • v-bind 给组件绑定参数,简写 :
  • 组件化

    • 组合组件slot插槽
    • 组件内部绑定事件需要使用到 this.$emit(“事件名”,参数);
    • 计算属性的特色,缓存计算数据

遵循Soc关注度分离原则,Vue是纯粹的视图框架,并不包含,比如Ajax之类的通信功能,为了解决通信问题,我们需要使用Axios框架做异步通信

  • 说明

    Vue的开发都是要基于NodeJS,实际开发采用vue-cli脚手架开发,vue-router路由,vuex做状态管理;Vue UI,界面我们一般使用ElementUI(饿了么出品),或者ICE(阿里巴巴出品)来快速搭建前端项目~~

    https://element.eleme.cn/#/zh-CN

    https://ice.work/

Vue-cli项目

  • vue-cli官方提供的一个脚手架,用于快速生成一个vue的项目模板

    预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个骨架项目就是脚手架,我们开发更加的快速

  • 主要功能

    • 统一目录结构
    • 本地调试
    • 热部署
    • 单元测试
    • 集成打包上线
  • 需要的环境

    确认nodejs安装成功:安装node自带npm 环境变量自动配置了

    • cmd 输入 node -v 查看是否能够正确打印出版本号
    • cmd 输入 npm -v 查看是否能够正确打印出版本号

    这个npm,就是一个软件包管理工具,就和linux下的apt软件安装差不多

    安装Node.js淘宝镜像加速器(cnpm) 这样子的话,下载会快很多,maven也是镜像的~

# -g 就是全局安装
npm install cnpm -g
# 或者使用如下语句解决 npm 速度慢的问题
npm install --registry=https://registry.npm.taobao.org

​ 安装位置C:UsersAdministratorAppDataRoaming
pm

​ c盘的隐藏目录 需要查看-都选隐藏文件

  • 安装vue-cli
cnpm install vue-cli -g
# 测试是否安装成功
# 查看可以基于那些模板创建vue应用程序,通常我们选择 webpack (这种打包方式可以兼用es5)
vue list

第一个vue-cli应用程序

  • cmd运行
vue init webpack myvue
#之后一直选NO
  • 初始化并运行
cd myvue

npm install
#不可以的话用这个
npm install --registry=https://registry.npm.taobao.org

#启动项目
npm run dev

#停止
ctrl + C

webpack学习

CommonsJS

def:服务器端的NodeJS遵循CommonsJS规范,该规范核心思想是允许模块通过require方法来同步加载所需依赖的其他模块,然后通过exports或module.exports来导出需要暴露的接口。

require("module");
require("../module.js");
export.doStuff = function(){};
module.exports= someValue;

优点

  • 服务器端模块便于重用
  • NPM中已经有超过45万个可以使用的模块包
  • 简单易用

缺点

  • 同步的模块加载方式不适合在浏览器环境中,同步意味着阻塞加载,浏览器资源是异步加载的
  • 不能非阻塞的并行加载多个模块

ES6模块

import "jQuery";//导入
export function doStuff(){}//暴露
module "localModule"{}//模块

优点

  • 容易进行静态分析
  • 面向未来的EcmaScript标准

缺点

  • 原生浏览器端还没有实现该标准
  • 全新的命令,新版的NodeJS才支持

实现

  • Babel

安装Webpack

webpack是一款模块加载器兼打包工具,它能把各种资源,如JS JSX ES6 SASS LESS 图片都作为模块来处理和使用。变成ES5 所有浏览器 都可用

安装

npm install webpack -g
npm install webpack-cli -g
#安装不成功后面加 --registry=https://registry.npm.taobao.org

#安装成功测试
webpack -v
webpack-cli -v

配置

创建 webpack-config.js 配置文件

  • entry:入口文件,指定WebPack用哪个文件作为项目的入口
  • output:输出,指定webpack把处理完成的文件放置到指定路径
  • module:模块,至于处理各种类型的文件
  • plugins:插件,如:热更新、代码重用等
  • resolve:设置路径指向
  • watch:监听,用于设置文件改动后直接打包

使用webpack

  • 创建项目
  • 创建一个名为 modules 的目录,用于放置JS模块等资源文件

webpack.config.js

module.exports = {
  entry:"./modules/main.js",
  output:{
      filename:"./js/bundle.js"
  }
};

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--前端的模块化开发-->
<script src="dist/js/bundle.js"></script>
</body>
</html>

modules目录下js文件

main.js

//require接受一个方法 接受完生成的对象  就可以调很多方法
var hello = require("./hello");
hello.sayHi();
hello.sayHi1();
hello.sayHi2();
hello.sayHi3();

cmd输入

webpack

就会在生成dist/js/bundle.js

hello.js

//暴露一个方法
exports.sayHi = function () {
    document.write("<h1>Summer</h1>")
}
exports.sayHi1 = function () {
    document.write("<h1>Summer</h1>")
}
exports.sayHi2 = function () {
    document.write("<h1>Summer</h1>")
}
exports.sayHi3 = function () {
    document.write("<h1>Summer</h1>")
}

vue-router路由

Vue Router 是 Vue.js 官方的路由管理器。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。

安装

vue-router是一个插件包,所以我们还是需要用npm/cnpm来进行安装的。打开命令工具,进入你的项目目录,输入下面的命令。

npm install vue-router --save-dev
# --registry=https://registry.npm.taobao.org

如果在一个模块化工程中使用它,必须要通过Vue.use()明确地安装路由功能:

//路由配置
import Vue from "vue";
import VueRouter from "vue-router";

//安装路由
Vue.use(VueRouter);

测试

1、先删除没用的东西

2、components 目录下存放我们自己编写的组件

3、定义一个Content.vue的组件

<template>
  <h1>内容页</h1>
</template>

<script>
export default {
  name: "Content"
}
</script>

<!--scoped作用域的意思-->
<style scoped>

</style>

4、安装路由,在src目录下,新建一个文件夹:router 专门存放路由

//路由配置
import Vue from "vue";
//导入路由插件
import VueRouter from "vue-router";
//导入自定义的组件
import Content from "../components/Content";
import Main from "../components/Main";

//安装路由
Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
  routes:[
    {
      //路由路径 类似@RequestMapping
      path:"/content",
      //路由名称
      name:"content",
      //跳转的组件
      component: Content
    },
    {
      //路由路径
      path:"/main",
      name:"main",
      //跳转的组件
      component: Main
    }
  ]
});

5、在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'//自动扫描里面的路由配置
//显示声明使用VueRouter

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  //让这个vue对象里面有路由 配置路由
  router,
  components: { App },
  template: '<App/>'
})

6、在App.vue中使用路由

<template>
  <div id="app">
    <h1>Vue-Router</h1>
    <router-link to="/main">首页</router-link>
    <router-link to="./content">内容页</router-link>
<!--  router-view是展示template-->
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

vue-快速上手

1、创建一个名为hello-vue的工程 vue init webpack hello-vue

2、安装依赖,我们需要vue-router、element-ui、sass-loader和node-sass四个插件

#进入工程目录
cd hello-vue

#安装vue-router
#--registry=https://registry.npm.taobao.org
npm install vue-router --save-dev --registry=https://registry.npm.taobao.org

#安装element-ui
npm i element-ui -S --registry=https://registry.npm.taobao.org

#安装依赖
npm install --registry=https://registry.npm.taobao.org

#安装SASS加载器
cnpm install sass-loader node-sass --save-dev --registry=https://registry.npm.taobao.org

#启动测试
npm run dev 

3、npm命令解释

  • npm install moduleName :安装模块到项目目录下
  • npm install -g moduleName :-g 的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看npm config prefix 的位置
  • npm install –save moduleName:–save 的意思是将模块安装到项目目录下,并在package文件的dependencies 节点写入依赖,-S为该命令的缩写
  • npm install –save-dev moduleName:–save-dev 的意思是将模块安装到项目目录下,并在package文件的devDenpendenies 节点写入依赖 -D 为该命令的缩写

4、代码

  • main.js 导入router element-ui 以及element-ui的css
import Vue from 'vue'
import App from './App'

import router from "./router";

import ElementUI from "element-ui";
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
Vue.use(router);
Vue.use(ElementUI)

new Vue({
  el: '#app',
  template: '<App/>',
  render: h => h(App),
  router
})

  • App.vue
<template>
  <div id="app">
    <h1>Summer</h1>
    <router-link to="/login">login</router-link>
    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'App'
}
</script>


  • router/index,js配置路由
import Vue from "vue";
import VueRouter from "vue-router";

import Login from "../views/Login";
import Main from "../views/Main"

Vue.use(VueRouter);

export default new VueRouter({
  routes:[
    {
      path:"/login",
      component:Login
    },
    {
      path:"/main",
      component:Main
    }
  ]
});


  • views/Login.vue
<template>
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="密码" prop="pass">
      <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model.number="ruleForm.age"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: '',
        checkPass: '',
        age: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        age: [
          { validator: checkAge, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>

</style>

  • views/Main.vue
<template>
  <h1>首页</h1>
</template>

<script>
export default {
  name: "main"
}
</script>

<style scoped>

</style>

网站推荐

element-ui:

组件 | Element

layui

layer 弹出层组件 – jQuery 弹出层插件 (layui.com)

docsify

Custom navbar (docsify.js.org)

路由嵌套

嵌套路由又称子路由,在实际应用中,通常有多层嵌套的组件而成。同样地,URL中各段动态路径也按某种结构对应嵌套的各层组件。例如:

用户登录/侧边栏

工程目录

1、创建用户信息组件 views/user/Profile.vue

<template>
  <h1>个人信息</h1>
</template>

<script>
export default {
  name: "UserProfile"
}
</script>

<style scoped>

</style>

2、创建用户列表组件 views/user/List.vue

<template>
  <h1>用户列表</h1>
</template>

<script>
export default {
  name: "UserList"
}
</script>

<style scoped>

</style>

3、修改首页视图,views/Main.vue 用element-ui的侧边栏【布局容器组件】

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <!--插入的地方-->
                <router-link to="/user/profile">个人信息</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <!--插入的地方-->
                <router-link to="/user/list">用户列表</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">分类管理</el-menu-item>
              <el-menu-item index="2-2">内容列表</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="3">
            <template slot="title"><i class="el-icon-caret-right"></i>系统管理</template>
            <el-menu-item-group>
              <el-menu-item index="3-1">用户设置</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人信息</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
        <el-main>
          <!--在这里展示视图-->
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
export default {
  name: "Main"
}
</script>
<style scoped lang="scss">
.el-header {
  background-color: #72a3e0;
  color: #333;
  line-height: 60px;
}
.el-aside {
  color: #333;
}
</style>

4、配置嵌套路由修改router/index.js 路由配置文件,使用children放入main中写入子模块

import Vue from "vue";
import VueRouter from "vue-router";

import Login from "../views/Login";
import Main from "../views/Main"

import List from "../views/user/List";
import Profile from "../views/user/Profile";

Vue.use(VueRouter);

export default new VueRouter({
  routes: [
    {
      path: "/login",
      component: Login
    },
    {
      path: "/main",
      component: Main,
      //嵌套路由
      children: [
        {
          path: "/user/profile",
          component: Profile
        },
        {
          path: "/user/list",
          component: List
        }
      ]
    }
  ]
});

5、在views/Login.vue 用element-ui的组件

注:这里sass-loader版本过高 修改package.json版本号为4.0.0

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onsubmit('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="温馨提示" :visible.sync="dialogVisiable" width="30%" :before-close="handleClose">
      <span>请输入账号和密码</span>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Login",
  data(){
    return{
      form:{
        username:'',
        password:''
      },
      //表单验证,需要在 el-form-item 元素中增加prop属性
      rules:{
        username:[
          {required:true,message:"账号不可为空",trigger:"blur"}
        ],
        password:[
          {required:true,message:"密码不可为空",tigger:"blur"}
        ]
      },

      //对话框显示和隐藏
      dialogVisible:false
    }
  },
  methods:{
    onSubmit(formName){
      //为表单绑定验证功能
      this.$refs[formName].validate((valid)=>{
        if(valid){
          //使用vue-router路由到指定界面,该方式称为编程式导航
          this.$router.push('/main');
        }else{
          this.dialogVisible=true;
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.login-box{
  border:1px solid #DCDFE6;
   350px;
  margin:180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
}
.login-title{
  text-align:center;
  margin: 0 auto 40px auto;
  color: #303133;
}
</style>

前端页面

参数传递及重定向

路由模式与404

路由模式有两种

  • hash:路径带#符号,如http://localhost/#/login
  • history:路径不带#符号,如http://localhost/login

修改路由配置如下

export default new Router({
    mode:'history',
    routes:[
        
    ]
});

处理404创建一个名为NotFound.vue的视图组件,代码如下:

<template>
<div>
  <h1>404~~你的页面走丢了</h1>
</div>
</template>

<script>
export default {
  name: "NotFound"
}
</script>

<style scoped>

</style>

配置路由

import Vue from "vue";
import VueRouter from "vue-router";

import Login from "../views/Login";
import Main from "../views/Main"

import List from "../views/user/List";
import Profile from "../views/user/Profile";
import NotFound from "../views/NotFound";

Vue.use(VueRouter);

export default new VueRouter({
  mode:'history',
  routes: [
    {
      path: "/login",
      component: Login
    },
    {
      path: "/main/:username",
      component: Main,
      props:true,
      //嵌套路由
      children: [
        {
          //v-bind绑定的 :id 这边来接受
          path: "/user/profile/:id",
          name:'Profile',
          component: Profile,
          props:true
        },
        {
          path: "/user/list",
          component: List
        },
        {
          path:"/goHome",
          redirect:"/login"
        }
      ]
    },
    {
      path:"*",
      component:NotFound
    }
  ]
});


路由钩子与异步请求

beforeRouteEnter:在进入路由前执行

beforeRouterLeave:在离开路由前执行

上代码:

<template>
<!--  所有的元素,必须不能在根节点下-->
<!--  这边来展示-->
  <div>
    <h1>个人信息</h1>
<!--    {{$route.params.id}}-->
    {{id}}
  </div>
</template>

<script>
export default {
  props:['id'],
  name: "UserProfile",
  //过滤器 chain
  beforeRouteEnter:(to,from,next)=>{
    console.log("进入路由之前");
    //业务代码
    next();
  },
  beforeRouteLeave:(to,from,next)=>{
    console.log("进入路由之后");
    //业务代码
    next();
  }
}
</script>

<style scoped>

</style>

参数说明:

  • to:路由将要跳转的路径信息
  • from:路由跳转前的路径信息
  • next:路由的控制参数
    • next() 跳入下一个页面
    • next(‘/path’) 改变路由的跳转方向,使其跳到另一个路由
    • next(false) 返回原来的页面
    • next((vm) => {}) 仅在beforeRouteEnter中可用,vm是组件实例

在钩子函数中使用异步请求

1、安装Axios

npm install --save axios vue-axios --registry=https://registry.npm.taobao.org

2、main.js 引用Axios

import Vue from 'vue'
import App from './App'

import router from "./router";

import ElementUI from "element-ui";
import 'element-ui/lib/theme-chalk/index.css';

import axios from 'axios';
import VueAxios from 'vue-axios'

//这里有顺序要求
Vue.use(VueAxios, axios);

Vue.config.productionTip = false
Vue.use(router);
Vue.use(ElementUI)

new Vue({
  el: '#app',
  template: '<App/>',
  render: h => h(App),
  router
})

3、profile.vue

<template>
  <!--  所有的元素,必须不能在根节点下-->
  <!--  这边来展示-->
  <div>
    <h1>个人信息</h1>
    <!--    {{$route.params.id}}-->
    {{ id }}
  </div>
</template>

<script>
export default {
  props: ['id'],
  name: "UserProfile",
  //过滤器 chain
  beforeRouteEnter: (to, from, next) => {
    console.log("进入路由之前");//加载数据
    //业务代码
    next(vm => {
      vm.getData();
    });
  },
  beforeRouterLeave: (to, from, next) => {
    console.log("进入路由之后");
    //业务代码
    next();
  },
  methods: {
    getData() {
      this.axios({
        method:"get",
        url:"http://localhost:8080/static/mock/data.json"
      }).then(function(response){
        console.log(response.data);
      });
    }
  }
}
</script>

<style scoped>

</style>

vue上项目

#使用这个命令必须 vue-cli是3.0+
vue create springboot-vue-demo

#--registry=https://registry.npm.taobao.org
npm uninstall vue-cli -g #先卸载
npm install @vue/cli -g  #在安装

#报Python错 可cmd尝试如下命令
npm install --global --production windows-build-tools --registry=https://registry.npm.taobao.org

#还不可以 安装2.7的python
#https://blog.csdn.net/u011781521/article/details/53909151


#安装element-plus
#用 vue-cli 4 工具创建了一个 Vue3 项目
npm install element-plus --save

#main.js引入element-plus
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';

.use(ElementPlus)

mian.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import '@/assets/css/global.css'
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';

import 'dayjs/locale/zh-cn'
import locale from 'element-plus/lib/locale/lang/zh-cn'

createApp(App).use(store).use(router).use(ElementPlus, { locale ,size:"small"}).mount('#app')

发表回复

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