Vue-cli
Vue-cli概述
Vue-cli是什么
vue-cli是官方提供的一个脚手架,能够快速生成vue的项目模板,类似于idea创建maven项目时从原型安装
Vue-cli的主要功能
Vue-cli的使用
Node.js
Nodejs 是基于 Chrome 的 V8 引擎开发的一个 C++ 程序,目的是提供一个 JS 的运行环境,也是说,nodejs服务于js,而vue相当于也是js框架
-
安装Node.js 在官网下载安装包,直接安装nodejs和npm在电脑上,自动配置环境变量
npm就是一个软件包管理工具,和linux下的apt差不多
-
在cmd里输入node -v和npm -v测试是否配置成功 -
安装NodeJs淘宝镜像加速器
npm install cnpm -g […] / rollbackFailedOptional: verb npm-session 79217def9fc7d9d0
这样安装不成功改用下面代码
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装成功后会存放在C:\Users\里的用户名\AppData\Roaming\npm\node_modules目录下 -
安装vue-cli
cnpm install vue-cli -g
安装完成后会和cnpm文件夹同名 -
安装完成后可以通过vue list查看所有模板
C:\Users\Michilay>vue list
Available official templates:
★ browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing. ★ browserify-simple - A simple Browserify + vueify setup for quick prototyping. ★ pwa - PWA template for vue-cli based on the webpack template ★ simple - The simplest possible Vue setup in a single HTML file ★ webpack - A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction. ★ webpack-simple - A simple Webpack + vue-loader setup for quick prototyping.
C:\Users\Michilay>
创建Vue-cli项目
-
打开要创建的目录 -
shift+右键打开prower shell -
输入cmd后vue init webpack vue-cli
E:\vue>vue init webpack vue-cli
? Project name vue-cli ? Project description A Vue.js project ? Author michlay ? 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) no
vue-cli · Generated “vue-cli”.
# Project initialization finished! # ========================
To get started:
cd vue-cli npm install (or if using yarn: yarn) npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
-
进入刚创建好的vue-cli内,cd vue-cli -
安装依赖cnpm install -
用idea打开 -
使用cnpm run dev 打包
E:\vue\vue-cli>cnpm run dev
> vue-cli@1.0.0 dev E:\前端自学\vue-cli > webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
10% 13% 13% 13% 13% 13% 13% building modules 30/33 modules 3 active …e&index=0!E:\前端自学\vue-cli\src\App.vue{ parser: “babylon” } is deprecated; we now treat it as { parser: “babel” }. 14% 14% 14% 95% emitting
DONE Compiled successfully in 4063ms 下午4:10:58
I Your application is running here: http://localhost:8080
-
在浏览器输入地址,出现vue的界面,出现Node.js的本地服务器(类似于Tomcat)即可 -
如果要停止在页面按下Ctrl+C
idea编辑内容
- 在idea打开该页面后,进入src则是代码的位置
- 修改components包下的HelloWorld.js的templete标签内代码
- 在下面控制台输入npm run dev即可修改成功
- 在localhost:8080查看页面
Vue项目结构
程序通过indexhtml和main.js里的组件绑定
main.js通过import App.vue导入appvue的组件,appvue的组件有屌用了Helloworld自定义组件,这个组件存在于components包内,也就是刚才更改代码的位置,加上一个img标签就是整个实现页面的内容
Webpack
Webpack概述
webpack是一款模块加载器兼打包工具,它可以把各种资源,比如js、jsx、es6、less、图片等都作为一个模块进行处理管理,方便使用
它的最大作用就是,将ES6的规范打包起来,如果代码是用了es6特性的代码,那么打包后可以在es5规范的浏览器上使用
Webpack安装
-
安装webpack
cnpm install webpack -g
-
安装webpack客户端
cnpm install webpack-cli -g
-
检测安装结果
C:\Users\Michilay>webpack -v webpack 5.51.1 webpack-cli 4.8.0
C:\Users\Michilay>webpack-cli -v webpack 5.51.1 webpack-cli 4.8.0
Webpack使用
-
新建一个空文件夹用idea打开 -
创建一个modules包 -
在modules包下写两个js文件 hello.js
exports.sayHi1= function (){
document.write("<h1>ES6规范1</h1>")
}
exports.sayHi2= function (){
document.write("<h1>ES6规范2</h1>")
}
exports.sayHi3= function (){
document.write("<h1>ES6规范3</h1>")
}
exports.sayHi4= function (){
document.write("<h1>ES6规范4</h1>")
}
exports.sayHi5= function (){
document.write("<h1>ES6规范5</h1>")
}
main.js var hello = require("./hello");
hello.sayHi1();
hello.sayHi2();
hello.sayHi3();
hello.sayHi4();
hello.sayHi5();
-
在主目录下新建webpack.config.js设置打包配置
module.exports = {
entry:'./modules/main.js',
output:{
filename:"./js/bundle.js"
}
}
-
在控制台输入webpack打包
PS E:\vue\webpack-study> get-ExecutionPolicy Restricted PS E:\vue\webpack-study> set-ExecutionPolicy RemoteSigned PS E:\vue\webpack-study> get-ExecutionPolicy RemoteSigned PS E:\vue\webpack-study> webpack asset ./js/bundle.js 1.84 KiB [emitted] (name: main) ./modules/main.js 116 bytes [built] [code generated] ./modules/hello.js 400 bytes [built] [code generated] webpack 5.51.1 compiled successfully in 96 ms
-
接着就会在项目的dist/js下出现bundle.js包含之前写的es6转换成es5的代码 -
新建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>
显示之前的js内容 -
如果现在修改代码,会有热部署,马上重新打包,如果要停止,在控制台按下Ctrl+C
Vue-router
Vue-router概述
vue router是vue.js官方的路由管理器,他的功能有
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的CSS class 的链接
- HTML5历史模式或hash模式,在IE9中自动降级
- 自定义的滚动条行为
Vue router使用
-
安装Vue router,在之前的vue项目下执行命令
PS E:\前端自学\vue-cli> cnpm install vue-router --save-dev √ Installed 1 packages √ Linked 1 latest versions √ Run 0 scripts √ All packages installed (1 packages installed from npm registry, used 590ms(network 587ms), speed 256.18KB/s, json 1(19.5KB), tarball 130.88KB)
-
在components里先写两个页面 Main.vue <template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
Content.vue <!--写页面的地方-->
<template>
<h1>内容页</h1>
</template>
<!--导入-->
<script>
export default {
name: "Content"
}
</script>
<!--如果加了scoped表示只在当前组件生效-->
<style scoped>
</style>
-
再在router包下新建index.js进行路由管理和配置 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',
name:'content',
component:Content
},
{
path:'/main',
name:'main',
component:Main
}
]
});
-
App.vue写主页内容 <template>
<div id="app">
<h1>Vue-Router</h1>
<router-link to="/main">首页 </router-link>
<router-link to="/content">内容页</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>
-
main.js里声明即可 import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
ElementUI
ui库,能和vue完美结合
项目构建
-
在要构建的目录下输入
PS E:\vue> vue init webpack vue-elm
? Project name vue-elm ? Project description A Vue.js project ? Author michilay ? 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) no
vue-cli · Generated “vue-elm”.
# Project initialization finished! # ========================
To get started:
cd vue-elm npm install (or if using yarn: yarn) npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
-
进入该目录安装router
PS E:\vue\vue-elm> cnpm install vue-router --save-dev √ Installed 1 packages √ Linked 1 latest versions √ Run 0 scripts √ All packages installed (1 packages installed from npm registry, used 6s(network 6s), speed 3.26KB/s, json 1(19.5KB), tarball 0B)
-
安装element-ui
PS E:\vue\vue-elm> cnpm i element-ui -S √ Installed 1 packages √ Linked 11 latest versions [1/1] scripts.postinstall element-ui@2.15.5 ? async-validator@1.8.5 ? babel-runtime@6.26.0 ? core-js@^2.4.0 run “node -e “try{require(’./postinstall’)}catch(e){}””, root: “E:\vue\vue-elm\node_modules\_core-js@2.6.12@core-js” Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
[1/1] scripts.postinstall element-ui@2.15.5 ? async-validator@1.8.5 ? babel-runtime@6.26.0 ? core-js@^2.4.0 finished in 148ms √ Run 1 scripts deprecate element-ui@2.15.5 ? async-validator@1.8.5 ? babel-runtime@6.26.0 ? core-js@^2.4.0 core-js@??.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js. √ All packages installed (11 packages installed from npm registry, used 5s(network 5s), speed 367.73KB/s, json 11(98.16KB), tarball 1.55MB)
-
安装所有的依赖
cnpm install
-
安装SASS加载器
cnpm install sass-loader node-sass --save-dev
-
安装成功后测试
npm run dev
-
idea打开
项目编写
-
views/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%
: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>
<style scoped>
</style>
-
views/Main.vue <template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
-
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
}]
});
-
App.vue 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
}]
});
-
main.js 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.use(router);
Vue.use(Element)
new Vue({
el: '#app',
router,
render: h => h(App)
})
-
开始构建 npm run dev -
如果有错误,修改 “sass-loader”: “^7.3.1”, -
如果还显示有错误,Node Sass version 6.0.1 is incompatible with ^4.0.0.,卸载重装node-sass
cnpm uninstall node-sass
cnpm install node-sass@4.14.1
路由嵌套
只改变局部的内容
-
修改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: #B3C0D1;
color: #333;
line-height: 60px;
}
.el-aside {
color: #333;
}
</style>
-
在user下写List.vue和Profile.vue <template>
<h1>用户列表页</h1>
</template>
<script>
export default {
name: "List"
}
</script>
<style scoped>
</style>
<template>
<h1>个人信息</h1>
</template>
<script>
export default {
name: "UserProfile"
}
</script>
<style scoped>
</style>
-
更改router/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
}]
});
总结:
这整段代码的执行流程
- 网页的进入入口时index.html
- index.html里有一个id为app的div区域
- main.js里vm对象对app进行了选择并且把App.vue插入进去;同时main.js还配置了router和element-ui
- App.vue提供App接口给第三步,同时定义了一个router-view
- router-view自动解析router包下的index.js,router进行跳转工作
- router下的index.js导入所有要写的页面,声明router,接着写跳转路由,这里在main下面定义了两个子路由
- 在Login.vue下点击登录有一个$router.push方法进入到main
- Main.vue下有两个router-link to到两个不同的子页面实现路由嵌套
参数传递及重定向
第一种方式
传递参数,将main.vue改动一排如下,如果id还要绑定
<router-link :to="{name:'/user/profile',params:{id:1}}">个人信息</router-link>
路由那边,就会接受这个id,修改如下
path:'/user/profile/:id',
在页面显示如下
<template>
<div>
<h1>个人信息</h1>
{{$route.params.id}}
</div>
</template>
第二种方式
在路由里声明
props:true,
页面直接通过props接收
<template>
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props:['id'],
name: "UserProfile"
}
</script>
<style scoped>
</style>
上面的内容都是转发,如果要改成重定向
重定向的路由如下
{
path:'/goHome',
redirect:'/main'
}
view层写个link进入
<router-link to="/goHome">回到首页</router-link>
如果要传递login界面的user呢
-
修改login页面的方法如下 this.$router.push("/main/"+this.form.username);
-
router路由配置改成如下内容 export default new Router({
routes:[{
path:'/main/:name',
component:Main,
props:true,
-
main.vue接受并且显示即可 <span>{{name}}</span>
</el-header>
<el-main>
<!--在这里展示视图-->
<router-view />
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
props:['name'],
name: "Main"
}
路由模式与404
路由模式分为两种
- 默认的就是hash:路径带#符号
- 还有一种history:路径不带#号
修改成history,在路由配置里,添加如下代码
export default new Router({
mode: 'history',
404配置
一般情况,vue页面搜索不到会显示空页面,要显示404必须自己定义
-
写一个404页面 <template>
<div>
<h1>404,找不到你的页面</h1>
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
-
配置路由 import NotFound from "../views/NotFound";
........
{
path:'*',
component:NotFound
}
路由钩子和异步请求
钩子函数
修改个人主页如下
<template>
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props:['id'],
name: "UserProfile",
//过滤器,request,reponse,chain
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前")
next();
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入路由之后")
next();
}
}
</script>
<style scoped>
</style>
在进入主页和离开主页会执行上面两个方法
异步请求
-
安装axios
cnpm install axios -s
cnpm install vue-axios -s
-
main.js里导入 import axios from 'axios';
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
-
导入json数据 -
钩子函数处拿到数据即可 <template>
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props:['id'],
name: "UserProfile",
//过滤器,request,reponse,chain
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/data.json'
}).then(function (response){
console.log(response);
})
}
}
}
</script>
<style scoped>
</style>
|