1.简介

element-ui 是饿了么前端出品的基于 Vue.js的 后台组件库,方便程序员进行页面快速布局和构建
官网: http://element-cn.eleme.io/#/zh-CN

2.举例

1.创建一个新的Vue-cli工程
注意:命令行都要使用管理员模式运行

vue init webpack hello-vue

在这里插入图片描述
2.安装依赖,我们需要安装vue-router、element-ui、sass-loader和node-sass四个插件

# 进入工程目录
cd hello-vue
# 安装 vue-router
npm install vue-router --save-dev
# 安装 element-ui
npm i element-ui -S
#安装依赖
npm install
# 安装SASS加载器
cnpm install sass-loader node-sass --save-dev
# 启动测试
npm run dev

在这里插入图片描述自定义布局:https://docsIfy.Js.org
在这里插入图片描述
Main.vue

<template>
  <div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" >
      <el-form-item  label="用户名" prop="name">
        <el-input v-model.number="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item  label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    data() {
      var checkName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        setTimeout(() => {callback();}, 1000);

      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      return {
        ruleForm: {
          pass: '',
          name: ''
        },
        rules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          name: [
            { validator: checkName, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //使用vue-router 路由到指定页面,,该方式称之为编程式导航
            this.$router.push("/main");
          } else {
            alert("error login");
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>

</style>


index.js

import Vue from 'vue'
import Router from 'vue-router'

import Main from '../views/Main'
import Login from '../views/Login'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes:[
    {
      path:'/main',
      name:'main',
      component:Main
    },

    {
      path:'/login',
      name:'login',
      component: Login
    }

  ]
});

main.js

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.use(ElementUI);

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

App.vue

<template>
  <div id="app">
   <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>

结果:
在这里插入图片描述
在这里插入图片描述

3.路由嵌套

在这里插入图片描述
遇见错误:
https://blog.csdn.net/qq_26230421/article/details/96426823
Profile.vue

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

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

<style scoped>

</style>

List.vue

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

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

<style scoped>

</style>

Main.vue组件自己到element-ui里找
主要

 <el-menu-item-group>
              <router-link to="/user/profile">个人信息</router-link>
            </el-menu-item-group>
            <el-menu-item-group>
              <router-link to="/user/list">用户列表</router-link>
            </el-menu-item-group>
             <el-col :span="8">
        <router-view/>
      </el-col>
<template>
  <div>
      <el-row class="tac">
      <el-col :span="4">
        <h5>首页</h5>
        <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose">
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>用户管理</span>
            </template>
            <el-menu-item-group>
              <router-link to="/user/profile">个人信息</router-link>
            </el-menu-item-group>
            <el-menu-item-group>
              <router-link to="/user/list">用户列表</router-link>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-col>

      <el-col :span="8">
        <router-view/>
      </el-col>
    </el-row>

  </div>

</template>

<script>
  export default {
    methods: {
      handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      }
    }
  }
</script>

<style scoped>

</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'

import Main from '../views/Main'
import Login from '../views/Login'
import UserProfile from '../views/users/Profile'
import UserList from '../views/users/List'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes:[
    {
      path:'/main',
      component:Main,
      //嵌套路由
      children:[
        {path:'/user/profile',component:UserProfile},
        {path:'/user/list',component:UserList}
      ]
    },

    {
      path:'/login',
      component: Login
    }

  ]
});

在这里插入图片描述

4.参数传递及重定向

参数传递

方法一:
Main.vue

 <el-menu-item-group>
              <!--name传组件名 params传递的参数-->
              <router-link :to="{name: 'UserProfile',params:{id: 1}}">个人信息</router-link>
</el-menu-item-group>

index.js

routes:[
    {
      path:'/main',
      component:Main,
      //嵌套路由
      children:[
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile},
        {path:'/user/list',component:UserList}
      ]
    },

Profile.vue

<template>
<!--  所有的元素必须在根节点下-->
  <div>
    <h1>个人信息</h1>
    {{$route.params.id}}
  </div>
</template>

在这里插入图片描述
方法二:
index.js


  routes:[
    {
      path:'/main',
      component:Main,
      //嵌套路由
      children:[
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]

Profile.vue

<template>
<!--  所有的元素必须在根节点下-->
  <div>
    <h1>个人信息</h1>
<!--    {{$route.params.id}}-->
    {{id}}
  </div>
</template>

<script>
    export default {
      props:['id'],
        name: "UserProfile"
    }
</script>

重定向

index.js

export default new Router({
  mode: 'history',
  routes:[
    {
      path:'/main',
      component:Main,
      //嵌套路由
      children:[
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]
    },

    {
      path:'/login',
      component: Login
    },{
    //重定向到登录页面
    path: '/logOut',
      redirect:'/login'
    }

  ]

Main.vue

<el-menu-item-group>
              <router-link to="/logOut">回到登录页</router-link>
            </el-menu-item-group>

在这里插入图片描述
登录时传递用户名
Login.vue

<script>
  export default {
    data() {
      var checkName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        setTimeout(() => {callback();}, 1000);

      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      return {
        ruleForm: {
          pass: '',
          name: ''
        },
        rules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          name: [
            { validator: checkName, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //使用vue-router 路由到指定页面,,该方式称之为编程式导航
            this.$router.push("/main/" + this.ruleForm.name);
      } else {
            alert("error login");
            return false;
          }
        });
      }
    }
  }
</script>

index.js

export default new Router({
  mode: 'history',
  routes:[
    {
      //接收参数
      path:'/main/:name',
      component:Main,
      props:true,
      //嵌套路由
      children:[
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]
    },

Main.vue

 <el-col :span="4">
        <h5>{{name}}首页</h5>
<script>
  export default {
    props:['name'],
    methods: {

在这里插入图片描述

5.404

1.在文件夹views下新建一个NotFound.vue

<template>
  <div>
    <h1>404,页面不存在</h1>
  </div>
</template>

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

<style scoped>

</style>

2.index.js

import NotFound from '../views/NotFound'
  {
      path: '*',
      component: NotFound
    }

在这里插入图片描述

6.路由钩子与异步请求Axios

beforeRouteEnter: 在进入路由前执行
beforeRouteLeave: 在离开路由前执行
在这里插入图片描述

Profile.vue代码:

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

在这里插入图片描述

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

1.安装Axios

npm install --save axios vue-axios
或
cnpm install axios -s

在这里插入图片描述
2.

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

Vue.use(VueAxios, axios)

在这里插入图片描述
data.json

{
  "name": "张三",
  "url": "https://www.baidu.com",
  "page": 1,
  "address": {
    "street": "洪崖洞",
    "city": "重庆市",
    "country": "中国"
  },
  "hobby": ["sing","dance","draw"]
}

在这里插入图片描述
Profile.vue

<template>
<!--  所有的元素必须在根节点下-->
  <div>
    <h1>个人信息</h1>
<!--    {{$route.params.id}}-->
    {{id}}
  </div>
</template>

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

<style scoped>

</style>

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐