Vue 实战快速上手

转载https://www.cnblogs.com/unremitting-efforts/p/13835464.html

Vue 实战快速上手

我们采用实战教学模式并结合ElementUI组件库,将所需知识点应用到实际中,以最快速度带领大家掌握Vue的使用

创建工程

注意:命令行都需要使用管理员模式运行

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

Vue 实战快速上手

  1. 安装依赖,需要安装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加载器(编译css文件)
cnpm install sass-loader node-sass --save-dev
# 启动测试
npm run dev
  1. 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文件的devDependencies节点写入依赖,-D为该命令的缩写

创建登录页面

  1. static:存放静态资源

Vue 实战快速上手

  1. 创建routerviews文件夹
  • router:存放路由主配置文件index.js
  • views:存放Vue视图组件
  • components:存放Vue功能组件
  • assets:存放资源文件

Vue 实战快速上手

  1. 创建首页视图,在views目录下创建一个名为Main.vue的视图组件

Vue 实战快速上手

<template>
    <div>首页</div>
</template>

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

<style scoped>

</style>
  1. 创建登录页视图,在views目录下创建一个名为Login.vue的视图组件,其中el-*的元素为ElementUI组件

Vue 实战快速上手

<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>
  1. 通过路由交互独立的组件

5.1 设置路由主配置文件index.js

Vue 实战快速上手

5.2 主函数main.js设置

5.2.1 导入路由主配置(中转站)

5.2.2 导入ElementUI配置

Vue 实战快速上手

5.3 App.vue组件中显示路由跳转界面

Vue 实战快速上手

注意:

启动时可能出现编译失败(The “path” argument must be of type string. Received undefined),原因是sass版本过高,去package.json文件中将sass版本降至7.3.1,然后重新npm install即可

Vue 实战快速上手

5.4 通过路由手动跳转页面(#表示路由)

  • 目前主页为空

Vue 实战快速上手

  • 手动跳转到main页面

Vue 实战快速上手

  • 手动跳转到login页面

Vue 实战快速上手

路由嵌套

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

Vue 实战快速上手

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

Vue 实战快速上手

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

Vue 实战快速上手

  1. 配置嵌套路由修改router目录下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/user/Profile'
import UserList from '../views/user/List'

Vue.use(Router)

export default new Router({
  routes: [
    {
      // 登录页
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      // 首页
      path: '/main',
      name: 'Main',
      component: Main,
      // 配置嵌套路由
      children: [
        {
          path: '/user/profile',
          component: UserProfile
        },
        {
          path: '/user/list',
          component: UserList
        }
      ]
    }
  ]
});

说明:主要在路由配置中添加children数组配置,用于在该组件下设置嵌套路由

  1. 修改首页视图,我们修改Main.vue视图组件,此处使用了ElementUI布局容器组件,代码如下:
<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>
            <e1-menu-item-group>
              <el-menu-item index="2-1">分类管理</el-menu-item>
              <el-menu-item index="2-2">内容列表</el-menu-item>
            </e1-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: #048bd1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>

参数传递及重定向

  1. 前端传入参数

Vue 实战快速上手

  1. 路由配置支持传递参数

Vue 实战快速上手

  1. 组件接收参数

Vue 实战快速上手

  1. 重定向

4.1 路由配置

Vue 实战快速上手

4.2 组件路由链接

Vue 实战快速上手

路由模式与404

  1. 路由模式有两种

修改路由配置,代码如下

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

2.1 新建NotFound组件

Vue 实战快速上手

2.2 路由配置

import NotFound from "../views/NotFound"

// routes中添加404路由配置
{
 path: '*', // 找不到的路径就走这里
 component: NotFound
}

路由钩子与异步请求

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

参数说明:

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

在钩子中使用异步请求

  1. 安装axios
npm install axios -s
  1. main.js中导入axios
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(axios, VueAxios)
  1. 准备数据:只有我们的static目录下的文件时可以被访问到的,所以我们把静态文件都放入到该目录下
// 静态数据存放的位置
static/mock/data.json // 测试数据一般放在static/mock文件夹下

Vue 实战快速上手

  1. 在beforeRouteEnter中进行异步请求

Vue 实战快速上手

<template>
  <div>
    <h1>个人信息</h1>
    {{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({
            methods: 'get',
            url: 'http://localhost:8080/static/mock/data01.json'
          }).then(function (response) {
            console.log(response)
          })
        }
      }
    }
</script>

<style scoped>

</style>
上一篇:express中使用art-template


下一篇:Django之路由层