Java开发应该掌握的Vue实际应用

Vue实战

声明:本文题材来自于狂神说https://www.bilibili.com/video/BV18E411a7mC

1、Vue-cli

1.1、什么是vue-cli

  • vue-cli官方提供的一个脚手架,用于快速生成一个vue的项目模板。
  • 预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个骨架项目就是脚手架,让我们的开发更加的快速。

主要的功能

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

1.2、需要的环境

1.2.1、nodejs

  • 安装Node.js:http://nodejs.cn/download/ 无脑下一步即可

  • 检验是否已经安装node -vnpm -v npm为软件包管理工具类似于linux下的apt软件安装

在这里插入图片描述

1.2.2、安装cnpm

cnpm是npm的国内加速器,属于淘宝镜像,因为npm有时下载非常的慢,切换国内镜像则会快很多。

# -g 就是全局安装
npm install cnpm -g

# 如果不想安装那么可以在需要下载软件包的时候声明使用淘宝镜像
npm install --registry=https://registry.npm.taobao.org

# 安装成功检验
cnpm -v

在这里插入图片描述

1.2.3、安装vue-cli

cnpm install vue-cli -g

#测试是否安装成功
#查看可以基于哪些模板创建vue应用程序,通常我们选择webpack
vue list

在这里插入图片描述

安装完成自动生成如下目录下的文件

在这里插入图片描述

1.3、第一个vue-cli应用程序

1.3.1、创建项目

在本地新建文件目录E:\ideaProject\vue-cli

1.3.2、初始化项目

  • 进入已经创建好的vue-cli目录
  • 执行初始化命令vue init webpack vue-cli

步骤说明:

  • Project name:项目名称,默认回车即可
  • Project description:项目描述,默认回车即可
  • Author:项目作者,默认回车即可
  • Vue build:可以箭头上下选,选第一个运行时编译即可
  • Install vue-router:是否安装vue-router,选择n不安装(后期需要再手动添加)
  • Use ESLint to lint your code:是否使用ESLint做代码检查,选择n不安装(后期需要再手动添加)
  • Set up unit tests:单元测试相关,选择n不安装(后期需要再手动添加)
  • Setupe2etests with Nightwatch:单元测试相关,选择n不安装(后期需要再手动添加)
  • Should we run npm install for you after the,project has been created:创建完成后直接初始化,选择n(箭头上下选择),我们手动执行

在这里插入图片描述

1.3.3、安装依赖

进入创建的vue-cli目录,同时执行命令npm install安装所需依赖

注意路径:初始化项目时新增了一个目录vue-cli所以需要进入vue-cli目录再安装所需依赖

在这里插入图片描述

1.3.4、启动项目

在vue-cli目录执行命令npm run dev,启动项目

在这里插入图片描述

1.3.5、访问项目

默认访问路径如下:http://localhost:8080/

在这里插入图片描述

2、Webpack

2.1、什么是Webpack

  • 本质上, webpack是一个现代JavaScript应用程序的静态模块打包器(module bundler) 。当webpack处理应用程序时, 它会递归地构建一个依赖关系图(dependency graph) , 其中包含应用程序需要的每个模块, 然后将所有这些模块打包成一个或多个bundle.
  • Webpack是当下最热门的前端资源模块化管理和打包工具, 它可以将许多松散耦合的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分离,等到实际需要时再异步加载。通过loader转换任何形式的资源都可以当做模块, 比如Commons JS、AMD、ES6、CSS、JSON、Coffee Script、LESS等;
  • 通俗的讲Webpack能够将ES6降级为ES5,去适应一些个别游览器的规则。

2.2、Webpack安装

npm install webpack -g
npm install webpack-cli -g

在这里插入图片描述

测试安装成功

  • webpack -v
  • webpack-cli -v

在这里插入图片描述

2.3、解析webpack.config.js

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

参考文件如下

module.exports = {
	entry:"",
	output:{
		path:"",
		filename:""
	},
	module:{
		loaders:[
			{test:/\.js$/,;\loade:""}
		]
	},
	plugins:{},
	resolve:{},
	watch:true
}

2.4、webpack应用

  1. 新建空白文件夹webpack用idea打开。

  2. 在idea中新建文件modules文件夹。

  3. 在modules中新建文件hello.js。

    // 暴露方法
    exports.sayHi=function () {
        document.write("<h1>hello webpack</h1>")
    }
    
  4. 在modules中新建main.js。

    // 引入方法
    var hello = require("./hello");
    hello.sayHi();
    
  5. 在工程根目录新建文件webpack.config.js。

    module.exports={
        entry:"./modules/main.js",
        output:{
            filename:"./js/bundle.js"
        }
    }
    
  6. 调出控制台webpack命令打包。

  7. 如果打包成功工程根目录会生成dist文件夹,里面有指定js/bundle.js文件,是打包后的文件。

  8. 在工程跟目录新建index.html引入打包后的js文件。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script src="./dist/js/bundle.js"></script>
    </body>
    </html>
    
  9. 查看index.html页面显示。

3、Vue-Router

3.1、什么叫Vue-Router

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

3.2、Vue-Router特点

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

3.3、如何使用Vue-Router

3.3.1、安装

第一次使用Vue-Router的话,可以在新项目下手动安装npm install vue-router --save-dev这个命令可以将vue-router集成到本项目中

3.3.2、使用

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

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

3.4、工程中应用

  1. 初始化一个项目执行初始化命令vue init webpack vue-router

  2. 安装vue-router到项目中npm install vue-router --save-dev

  3. 在目录新建文件夹components 用于存放自定义组件。

  4. 定义组件Content.vue

    <template>
        <div>
          <h1>内容页</h1>
        </div>
    </template>
    
    <script>
        // 暴露组件
        export default {
            name: "Content"
        }
    </script>
    <!--定义作用域-->
    <style scoped>
    
    </style>
    
  5. 定义组件Main.vue

    <template>
        <div>
          <h1>首页</h1>
        </div>
    </template>
    
    <script>
        export default {
            name: "Main"
        }
    </script>
    
    <style scoped>
    
    </style>
    
  6. 在根目录新建文件夹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:[
         {
           path:"/content",// 请求的路径
           component:Content // 转到执行的组件
         },{
           path:"/main",
           component:Main
         }
       ]
    })
    
  7. 在根目录中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'
    // 引用路由 这里路径可以简写为./router 默认指定到目录的index.js
    import router from "./router/index"
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      // 直接配置路由
      router,
      components: { App },
      template: '<App/>'
    })
    
    
  8. 在App.vue中使用路由

    <template>
      <div id="app">
          <!-- router-link 默认会被渲染成一个<a>标签,to属性为指定链接 
    		   router-view:用于渲染路由匹配到的组件
    	  -->
           <router-link to="/main">首页</router-link>
           <router-link to="/content">内容</router-link>
           <router-view></router-view>
      </div>
    </template>
    
    <script>
    
    export default {
      name: 'App',
      components: {
    
      }
    }
    </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. 测试…略

4、Vue整合练习

4.1、基础环境搭建

  1. 初始化工程vue init webpack hello-vue

  2. 安装依赖vue-router、element-ui、sass-loader和node-sass四个插件chongshi

    #进入工程目录中执行如下命令  需要注意的是如果npm安装失败请使用cnpm重试
    
    #安装vue-routern 
    npm install vue-router --save-dev
    #安装element-ui
    npm i element-ui -S
    # 安装SASS加载器
    cnpm install sass-loader node-sass --save-dev
    #安装依赖
    npm install
    
  3. 命令描述

    • 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为该命令的缩写。
  4. 删除无用模块,如下目录结构即可

    • assets:用于存放静态资源文件,图片logo之类
    • components:用于存放Vue功能组件
    • view:用于存放Vue视图组件
    • router:用于存放vue-router配置

在这里插入图片描述

  1. 在view模块中创建视图模块Main.vue

    <template>
        <div>
          <h1>首页</h1>
        </div>
    </template>
    
    <script>
        export default {
            name: "Main"
        }
    </script>
    
    <style scoped>
    
    </style>
    
  2. 在view模块中创建视图模块Login.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%">
          <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>
    
    
  3. 在router路由模块中创建index.js配置

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter);
    
    import Main from '../view/Main'
    import Login from '../view/Login'
    
    export default new VueRouter({
      routes:[
        {
          path:'/login',
          component:Login
        },{
          path: '/main',
          component: Main
        }
      ]
    });
    
    
  4. 在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/index'
    
    import ElementUI from 'element-ui'
    import 'element-ui/lib/theme-chalk/index.css'
    // 引入路由组件和element组件一定要记得使用
    Vue.use(router)
    Vue.use(ElementUI)
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      render:h=>h(App)
    })
    
  5. 在App.vue中展示界面

    <template>
      <div id="app">
          <router-view></router-view>
      </div>
    </template>
    
    <script>
    
    export default {
      name: 'App',
      components: {
    
      }
    }
    </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>
    
  6. 测试

  7. 错误场景一

    如果执行命令npm run dev出现如下错误

在这里插入图片描述

sass-loader版本太高需要降版本为^7.3.1,在项目中文件package.json中操作,调整完重新`npm install`或者`cnpm install`,测试发现一般需要用`cnpm install`才能成功。
  1. 错误场景二

    如果执行命令npm run dev出现如下情况

在这里插入图片描述

​ 直接将现有版本卸载npm uninstall node-sass然后降级版本 cnpm install node-sass@4.14.1

4.2、路由嵌套

4.2.1、什么叫路由嵌套

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

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

4.2.2、实例展示

1、在 views/user 目录下创建一个名为 Profile.vue 的视图组件

<template>
    <div>
      <h1>用户信息</h1>
    </div>
</template>

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

<style scoped>

</style>

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

<template>
    <div>
      <h1>用户信息列表</h1>
    </div>
</template>

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

<style scoped>

</style>

3、配置嵌套路由,修改 router 目录下的 index.js 路由配置文件

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

import Main from '../view/Main'
import Login from '../view/Login'

import userList from '../view/user/List'
import userProfile from '../view/user/Profile'

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

4、修改首页视图,修改 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="/userProfile">个人信息</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <router-link to="/userLit">用户列表</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: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

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

4.3、参数传递

4.3.1、$route方式

修改路由设置index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

import Main from '../view/Main'
import Login from '../view/Login'

import userList from '../view/user/List'
import userProfile from '../view/user/Profile'

export default new VueRouter({
  routes:[
    {
      path:'/login',
      component:Login
    },{
      path: '/main',
      component: Main,
      children:[
        {
          path:"/userLit",
          component:userList
        },
        {
          path:"/userProfile/:id",
          name:"userProfile",
          component:userProfile
        }
      ]
    }
  ]
});

修改参数传递Main.vue

<router-link :to="{name:'userProfile',params:{id:1}}">个人信息</router-link>

新增参数接收

<template>
    <div>
      <h1>用户信息 {{$route.params.id}}</h1>
    </div>
</template>

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

<style scoped>

</style>

4.3.2、props 的方式

修改路由配置index.j使用props方式传参

{
          path:"/userProfile/:id",
          name:"userProfile",
          component:userProfile,
          props: true
}

修改个人信息路由模块Profile.vue,定义接收参数

<template>
    <div>
      <h1>用户信息 {{id}}</h1>
    </div>
</template>

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

<style scoped>

</style>

传参按照原样不需要改变

4.4、请求方式

4.4.1、转发

上面配置路由的方式都是转发

4.4.2、重定向

新增导航栏用于测试重定向模块,修改Main.vue

<el-menu-item index="1-3">
     <router-link to="/goHome">回到首页</router-link>
</el-menu-item>

修改路由配置

{
      path:"/goHome",
      redirect:"/main"
}

4.5、路由模式与 404

4.5.1、路由模式

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

    • 默认为hash路由模式

      export default new Router({
        routes: []
      })
      
  • history:路径不带 # 符号,如 http://localhost/login

    • history路由模式

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

4.5.2、404配置

在view文件夹中新增404页面NotFound.vue

<template>
    <h1>404~网页走丢了</h1>
</template>

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

<style scoped>

</style>

修改路由配置index.js

// 修改内容
import notFound from '../view/NotFound'

{
    path:"*",
    component:notFound
}

4.6、路由钩子

  • beforeRouteEnter:在进入路由前执

  • beforeRouteLeave:在离开路由前执行

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

参数说明:

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

4.7、异步请求

  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目录,在该目录新建mock文件夹,新建data.js文件

    {
      "name": "axios",
      "url": "http://www.baidu.com",
      "page": 1,
      "isNonProfit": true,
      "address": {
        "street": "太平街道",
        "city": "长沙市",
        "country": "中国"
      },
      "links": [
        {
          "name": "vue",
          "url": "https://cn.vuejs.org/v2/guide/instance.html"
        },
        {
          "name": "axios",
          "url": "http://www.axios-js.com/zh-cn/docs/"
        }
      ]
    }
    
  4. 运行npm run dev启动项目,如果报错,如下

在这里插入图片描述

  1. 重新安装axioscnpm install --save vue-axios

  2. 编写异步请求代码

    <template>
        <div>
          <h1>用户信息 {{name}}</h1>
        </div>
    </template>
    
    <script>
      export default {
        name: "UserProFile",
        props: ['name'],
        beforeRouteEnter: (to,from,next) => {
          console.log('进入路由之前');//加载数据
          next(vm => {
            vm.getData();//进入路由之前执行getData()
          })
        },
        beforeRouteLeave: (to,from,next) => {
          console.log('离开路由之前');
          next()
        },
        methods: {
          getData() {
            // 不用this点会报错,不认识axios
            this.axios.get("http://localhost:8080/static/mock/data.json").then(function (response) {
               console.log(response.data);
            })
          }
        }
      }
    </script>
    
    <style scoped>
    
    </style>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值