【前端】vue学习5 : vue + ElementUI

vue+elementUI 项目搭建


命令行需要管理员权限。
根据之前创建vue-cli项目一样再来一遍 创建项目。
1、创建一个名为 hello-vue 的工程 vue init webpack vue-element

D:\IdeaProjects\vue>vue init webpack vue-element
‘git’ �����
? Project name vue-element
? Project description 回车
? Author 作者名
? Vue build standalone
? Install vue-router? No
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run npm install for you after the project has been created? (recommended) npm


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

# 进入工程目录
cd vue-element
# 安装 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	

3、创建成功后用idea打开,并删除净东西 创建views和router文件夹用来存放视图和路由
在这里插入图片描述


4、在views创建Main.vue
Main.vue

<template>
<h1>首页</h1>
</template>

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

<style scoped>
</style>


5、views中创建Login.vue视图组件
Login.vue(用的饿了么UI中的代码)

<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="dialogVisible"
      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: '密码不可为空', trigger: '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;
    width: 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>


6、创建路由,在 router 目录下创建一个名为 index.js 的 vue-router 路由配置文件
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({
  routes:[
    {
      path:'/Main',
      component:Main
    },
    {
      path:'/Login',
      component:Login
    }
  ]
});


7、在main.js中配置相关
main.js main.js是index.html调用的 所以基本上所有东西都导出到这
一定不要忘记扫描路由配置并将其用到new Vue中

// 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 Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false

Vue.use(router);
Vue.use(Element);


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render: h => h(App)
})


8. 在App.vue中配置显示视图
App.vue

<template>
  <div id="app">
    <router-link to="/Main">main</router-link>
    <router-link to="/Login">Login</router-link>
    <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>


9、最后效果

在这里插入图片描述


图 vue+elementUI实战效果图
测试:在浏览器打开 http://localhost:8081/#/Login
如果出现错误: 可能是因为sass-loader的版本过高导致的编译错误,当前最高版本是8.0.2,需要退回到7.3.1 ;
去package.json文件里面的 "sass-loader"的版本更换成7.3.1,然后重新cnpm install就可以了;然后npm run dev 即可启动项目。


路由嵌套

嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。

1、 创建用户信息组件,在 views/user 目录下创建一个名为 Profile.vue 的视图组件;
Profile.vue

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

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

<style scoped>

</style>

2、在用户列表组件在 views/user 目录下创建一个名为 List.vue 的视图组件;
List.vue

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

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

<style scoped>

</style>


3、 修改首页视图,我们修改 Main.vue 视图组件,此处使用了 ElementUI 布局容器组件,代码如下:
Main.vue

<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-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: pink;
    color: #333;
    line-height: 60px;
  }
  .el-aside {
    color: #333333;
  }
</style>


4、 配置嵌套路由修改 router 目录下的 index.js 路由配置文件,使用children放入main中写入子模块,代码如下
index.js

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

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

import UserList from '../views/user/List'
import UserProfile from '../views/user/Profile'


Vue.use(Router);

export default new Router({
  routes:[
    {
      path:'/Main',
      component:Main,
      children:[
        {
          path:'/user/profile',
          component:UserProfile
        },
        {
          path:'/user/list',
          component:UserList
        }
      ]
    },
    {
      path:'/Login',
      component:Login
    }
  ]
});


5、 路由嵌套实战效果图
在这里插入图片描述


参数传递

  • 这里演示如果请求带有参数该怎么传递

第一种取值方式

1、 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符

/src/router/index.js

{
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile
}

2、传递参数
此时我们在Main.vue中的route-link位置处 to 改为了 :to,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;

Main.vue 部分代码

<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:31}}">个人信息</router-link>

3、在要展示的组件Profile.vue中接收参数 使用 {{$route.params.id}}来接收
Profile.vue 部分代码

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

第二种取值方式 使用props 减少耦合

1、修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性,跳转到哪个component,就去对应的component接收属性

{
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile, 
	props: true
}

2、与第一种方式一样。 在Main.vue中修改route-link地址

<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

3、在Profile.vue接收参数为目标组件增加 props 属性
Profile.vue
使用方式不同、props接收

<template>
  <div>
    <h1>个人信息</h1>
    <h2>传递的id:{{id}}</h2>
  </div>
</template>

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

<style scoped>

</style>

效果图
在这里插入图片描述


实例:登录传递用户名

Login.vue 请求

this.$router.push("/main");
更改为以下
this.$router.push("/main/"+this.form.username);

在这里插入图片描述


组件重定向

Vue 中的重定向是作用在路径不同但组件相同的情况下。
router/index.js中添加即可。

   {
     path:'/goHome',
     redirect:'/'
   }

App.vue ,添加一个路由路径,请求/goHome,然后被重定向到/ ,即。localhost:8080

<template>
  <div id="app">
    <router-link to="/Main">main</router-link>
    <router-link to="/Login">Login</router-link>
    <router-link to="/goHome">goHome</router-link>
    <router-view></router-view>
  </div>
</template>

路由模式与 404

路由模式

路由模式有两种

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

router/index.js 中修改路由配置,代码如下:

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

在这里插入图片描述


404

1.创建一个NotFound.vue视图组件
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
}

3.效果图

在这里插入图片描述


路由钩子与异步请求

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行

在Profile.vue中写

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

参数说明:

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

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

1、安装 Axios

cnpm install --save vue-axios

2、main.js引用 Axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

3、准备数据 : 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。
数据和之前用的json数据一样 需要的去上述axios例子里

// 静态数据存放的位置
static/mock/data.json

4.在 beforeRouteEnter 中进行异步请求
Profile.vue

<template>
  <div>
    <h2>传递的json:{{info}}</h2>
  </div>
</template>

<script>
  export default {
    name: "UserProfile",
    props: ['id','info'],//接收info
    beforeRouteEnter: (to, from, next) => {//进入之前
      console.log("进入路由之前");
      next(vm => {
        vm.getData();
      });
    },
    beforeRouteLeave: (to, from, next) => {//进入之后
      console.log("进入路由之后");
      next();
    },
    methods: {
      getData: function () {
      //链式编程。
        this.axios.get('http://localhost:8080/static/mock/data.json').then(result => (this.info = result.data));
      }
    }
  }
</script>

<style scoped>

</style>


  • 非链式的axios
    methods: {
      getData: function () {
        this.axios({
          method: 'get',
          url: 'http://localhost:8080/static/mock/data.json'
        }).then(function (response) {
          console.log(response)
        })
      }
    }

5.路由钩子和axios结合图

在这里插入图片描述

在这里插入图片描述


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickkkkkkkkk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值