Vue是一套用于构建用户界面的渐进式框架,发布于2014年2月。与其他大型框架不同的是,Vue被设计为可以自底而上逐层应用。Vue的核心库只关注视图层,不仅易于上手,还便于与第三方库(如:vue-router:跳转,vue-resource:通信,vuex:管理)或既有项目整合
官网:https://cn.vuejs.org/v2/guide/
网络通信:axios
页面跳转:vue-router
状态管理:vuex
前端三要素
CSS预处理器定义了一种新的语言,其基本思想是,用一种专门的编程语言,为CSS增加了一些编程的特性,将CSS作为目标生成文件,然后开发者就只要使用这种语言,进行CSS的编码工作。也就是用一种专门的编程语言,进行Web页面样式设计,再通过编译器转化为正常的CSS文件,以供项目使用
常用的CSS预处理器
主要目的是实现一套代码三端统一(PC, Android:.apk、iOS:.ipa)并能够调用到设备底层硬件(如:传感器、GPS、摄像头等),打包方式主要有以下两种:
云打包:HBuild->HBuildX,DCloud出品;API Cloud
本地打包:Cordova(前身是PhoneGap)
WeUI
NodeJS框架及项目管理工具如下:
Vue.js
iview是一个强大的基于Vue的UI库,有很多实用的基础组件比elementui的组件更丰富,主要服务于PC界面的中后台产品,使用单文件的Vue组件化开发模式,基于npm+webpack+babel开发,支持ES2015高质量、功能丰富友好的API,自由灵活的使用空间
ElementUI是饿了么前端开源维护的VueUI组件库,组件齐全,基本涵盖后台所需的所有组件,文档讲解详细,例子也很丰富,主要用于开发PC端的页面,是一个质量比较高的VueUI组件库
在MVVM架构中,是不允许数据和视图直接通信的,只能通过ViewModel来通信,而ViewModel就是定义了一个Observer观察者
vue.js就是一个MVVM的实现者,他的核心就是实现了DOM监听与数据绑定
开发工具
Vscode
Hbuilder
Sublime
WebStorm
IDEA:插件vue 安装vue插件 Setting 新建File and Coding Templates -》 Vue Component ,(复制 Vue Single File Component)这样右键就有VueComponent
vue CDN
以下推荐国外比较稳定的两个 CDN,国内还没发现哪一家比较好,目前还是建议下载到本地。
Staticfile CDN(国内) : https://cdn.staticfile.org/vue/2.2.2/vue.min.js
unpkg:https://unpkg.com/vue/dist/vue.js, 会保持和 npm 发布的最新的版本一致。
cdnjs : https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js
jsdeliver:https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js
jsdeliver:https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js
新建demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--viw层,模板-->
<div id="app">
{{message}}
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
//Model:数据
data:{
message:"hello,vue!"
}
});
</script>
</body>
</html>
浏览器按F12 Console 可以修改vm.messsage值,页面发生变化
>vm.message="dd"
<"dd"
MVVM(Model-View-ViewModel)是一种软件架构设计模式,由微软WPF(用于替代WinForm,以前就是用这个技术开发桌面应用程序的)和Silverlight(类似于Java Applet,简单说就是在浏览器上运行的WPF)的架构师Ken Copper和Ted Peters开发,是一种简化用户界面的事件驱动编程方式,由John Gossman(同样也是WPF和Silverlight的架构师)于2005年在他的博客上发表
MVVM源自于经典的MVC(Model-VIew-Controller)模式,MVVM的核心就是ViewModel层,负责转换Model中的数据对象来让数据变得更容易管理和使用,其作用如下:
MVVM模式和MVC模式一样,主要的目的是分离视图(View)和模型(Model),有几大好处
可以使用v-bind来绑定元素特性
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<span v-bind:title="message">
鼠标悬停几秒钟查看此处动态绑定的提示信息
</span>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data:{
message:"hello,vue!"
}
});
</script>
</body>
</html>
v-bind等被称为指令,指令带有前缀v-,以表示它们是Vue提供的特殊特性。它们会在渲染的DOM上应用特殊的响应式行为。在这里,该指令的意思是:将这个元素节点的title特性和Vue实例的message属性保持一致
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h1 v-if="ok">YES</h1>
<h1 v-else>NO</h1>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data:{
ok: true
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h1 v-if="type==‘A‘">A</h1>
<h1 v-else-if="type==‘B‘">B</h1>
<h1 v-else>C</h1>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data:{
type: ‘D‘
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<li v-for="item in items">{{item.message}}</li>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data:{
items: [
{message: ‘ming‘},
{message: ‘hello‘}
]
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<button v-on:click="sayHi">Click Me</button>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data: {
message: ‘ming‘
},
methods: {//方法必须定义在Vue的Methods对象中
sayHi: function (event){
alert(this.message);
}
}
});
</script>
</body>
</html>
Vue七个属性
Vue.js是一个MVVM框架,即数据双向绑定,即当数据发生变化的时候,视图也就发生变化,当视图发生变化的时候,数据也会跟着同步变化
数据双向绑定,一定是对于UI控件来说的,非UI控件不会涉及到数据双向绑定,单项数据绑定是使用状态管理工具的前提,如果我们使用vuex,那么数据流也是单项的,这时就会和双向数据绑定有冲突
v-model双向绑定
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
输入的文本:<input type="text" v-model="message">{{message}}
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el:"#app",
data: {
message: ‘ming‘
}
});
</script>
</body>
</html>
组件时可复用的Vue实例
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<!--组件,传递给组件中的值:props-->
<ming v-for="item in items" v-bind:mm="item"></ming>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script>
//定义一个Vue组件 component
Vue.component("ming",{
props: [‘mm‘],
template: ‘<li>{{mm}}</li>‘
});
var vm = new Vue({
el:"#app",
data: {
items: ["Java","Linux","Mysql"]
}
});
</script>
</body>
</html>
Axios是一个开源的可以用在浏览器端和NodeJS的异步通信框架,她的主要作用就是实现Ajax异步通信,其功能特点如下
Github:https://github.com/axios/axios/
在线cdn:https://unpkg.com/axios/dist/axios.min.js
Vue.js是一个视图层框架,并不包含Ajax的通信功能
推荐使用Axios框架,少用jQuery,因为它操作DOM太频繁
创建一个data.json的文件
{
"name": "ming",
"url": "https://www.baidu.com",
"page": 1,
"address": {
"street": "11",
"city": "福建厦门",
"country": "中国"
},
"links": [
{
"name": "bilibili",
"url": "https://space.bilibili.com/111"
},
{
"name": "Java",
"url": "https://space.bilibili.com/111"
},
{
"name": "Mysql",
"url": "https://space.bilibili.com/111"
}
]
}
Vue实例有一个完整的生命周期,也就是从开始创建,初始化数据,编译模板,挂载DOM,渲染->更新->渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期
在Vue的整个生命周期中,它提供了一系列的事件,可以让我们在事件触发时注册JS方法,可以让我们用自己注册的JS方法控制整个大局,在这些事件响应方法中的this直接指向的是Vue的实例
钩子函数
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--v-v-clock:解决闪烁问题-->
<style>
[v-clock]{
display: none;
}
</style>
</head>
<body>
<div id="vue" v-clock>
<div>{{info.name}}</div>
<a v-bind:href="info.url">点我</a>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
var vm = new Vue({
el:"#vue",
data() {//data方法 这里不是属性
return {
//请求的返回参数格式,必须和json字符串一样 可以不写,不能写错
info: {
name: null,
address: {
country: null,
city: null,
street: null
},
url: null
}
}
},
mounted() {//钩子函数 链式编程,ES6
axios.get(‘data.json‘)
.then(response =>(this.info = response.data));
}
});
</script>
</body>
</html>
Vue:计算属性、内容分发、自定义事件
计算属性的重点突出在属性两个字上(属性是名词),首先它是个属性,其次这个属性有计算的能力(计算式动词),这里的计算就是个函数,简单点说,它就是一个能够将计算结果缓存起来的属性(将行为转化成了静态的属性),仅此而已,可以想象为缓存
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--v-v-clock:解决闪烁问题-->
<style>
[v-clock]{
display: none;
}
</style>
</head>
<body>
<div id="vue" v-clock>
<p>{{currentTime2}}</p>
<p>{{currentTime1()}}</p>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script type="text/javascript">
var vm = new Vue({
el:"#vue",
data: {
message: ‘hello,ming‘
},
methods: {
currentTime1: function (){
return Date.now();//返回一个时间戳
}
},
computed: {//计算属性: methods,computed 方法名不能重名,重名之后,只会调用methods方法
currentTime2: function (){
return Date.now();//返回一个时间戳
}
}
});
</script>
</body>
</html>
computed:会缓存,如果中间的数据刷新,缓存失效,重新计算
在Vue.js中我们使用
比如准备制作一个待办事项组件(todo),该组件由待办标题(todo-title)和待办内容(todo-items)组成,但这三个组件又是相互独立的,该如何操作呢
v-bind 简写 :
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items>
</todo>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script type="text/javascript">
//slot:插槽
Vue.component(‘todo‘,{
template:
‘<div> <slot name="todo-title"></slot> <ul> <slot name="todo-items"></slot> </ul> <div>‘
});
Vue.component(‘todo-title‘,{
props: [‘title‘],
template: ‘<div>{{title}}</div>‘
});
Vue.component(‘todo-items‘,{
props: [‘item‘],
template: ‘<li>{{item}}</li>‘
});
var vm = new Vue({
el: ‘#vue‘,
data: {
title: ‘书籍列表‘,
todoItems: [‘Java‘,‘Python‘,‘Linux‘]
}
});
</script>
</body>
</html>
v-onclick 简写 @click
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems" :item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
<!--1.导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
<script type="text/javascript">
//slot:插槽
Vue.component(‘todo‘,{
template:
‘<div> <slot name="todo-title"></slot> <ul> <slot name="todo-items"></slot> </ul> <div>‘
});
Vue.component(‘todo-title‘,{
props: [‘title‘],
template: ‘<div>{{title}}</div>‘
});
Vue.component(‘todo-items‘,{
props: [‘item‘,‘index‘],
//只能绑定当前组件的方法
template: ‘<li>{{index}}---{{item}} <button @click="remove">删除</button></li>‘,
methods: {
remove: function (index){
//this.$emit 自定义事件分发
this.$emit(‘remove‘,index);
}
}
});
var vm = new Vue({
el: ‘#vue‘,
data: {
title: ‘书籍列表‘,
todoItems: [‘Java‘,‘Python‘,‘Linux‘]
},
methods: {
removeItems: function (index){
this.todoItems.splice(index,1);//一次删除一个元素
}
}
});
</script>
</body>
</html>
核心:数据驱动,组件化
优点:借鉴了AngulaJS的模块化开发和React的虚拟Dom,虚拟Dom就是把Dom操作放到内存中执行
遵循SoC关注度分离原则,Vue式纯粹的视图框架,并不包含,比如Ajax之类的通信功能,为了解决通信问题,我们需要使用Axios框架做异步通信
Vue的开发都是要基于NodeJS,实际开发采用vue-cli脚手架开发,vue-router路由,vuex做状态管理;Vue UI,界面我们一般使用ElementUI (饿了么出品),或者ICE(阿里巴巴出品)来快速搭建前端项目
vue-cli是官方提供的一个脚手架,用于快速生成一个vue的项目模板
预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个骨架项目就是脚手架,我们的开发更加的快速
主要的功能:
Node.js http://nodejs.cn/download/
安装就无脑下一步就好,安装在自己的环境目录下
确认nodejs安装成功:
这个npm就是一个软件包管理工具,就和linux下的apt软件安装差不多
安装Node.js 淘宝镜像加速器(cnpm)
这样子的话,下载会快很多~
npm install cnpm -g # -g就是全局安装
#或使用如下语句解决npm速度慢的问题
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装的位置(我nodejes选的是nodejs zip包免安装)
D:\envoronment\node-v14.15.0-win-x64\node_modules
安装vue-cli
cnpm install vue-cli -g #可以cnpm install vue-cli -g
#测试是否安装成功
#查看可以基于哪些模板创建vue应用程序,通常我们选择 webpack
vue list
创建一个Vue项目,我们随便建立一个空的文件夹在电脑上,我这里在D盘下新建一个目录D:\project\vue-study
创建一个基于webpack模块的vue应用程序
#这里的myvue是项目名称,可以根据自己的需求起名
vue init webpack myvue
C:\Users\Administrator\Desktop\vue\vue-study>vue init webpack myvue
? Project name myvue
? Project description A Vue.js project
? Author ming <xxx@qq.com>
? 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 "myvue".
# Project initialization finished!
# ========================
To get started:
cd myvue
npm install (or if using yarn: yarn)
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
一路选择no即可
创建了myvue项目,目录下有许多文件
说明:
Project name:项目名称,默认回车即可
Project description:项目描述,默认回车即可
Author:项目作者,默认回车即可
Install vue-router:是否安装vue-router,选择n不安装(后期需要再手动添加)
Use ESLint to lint your code:是否使用ESLint做代码检查,选择n不安装(后期需要再手动添加)
Set up unit tests:单元测试相关,选择n不安装(后期需要再手动添加)
Set up e2e tests with Nightwatch:单元测试相关,选择n不安装(后期需要再手动添加)
Should we run npm install for you after the project has been created:创建完成后直接初始化,选择n,我们手动执行;运行结果
cd myvue
cnpm install #安装依赖包
cnpm run dev
访问 http://localhost:8080/ 得到vue网页
用IDEA打开myvue,查看工程结构
本质上,webpack是一个现代JavaScript应用程序的静态模块打包器(module bundler)。当webpack处理应用程序时,它会递归的构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个bundler
Webpack是当下最热门的前端资源模块化管理和打包工具,它可以将许多松散耦合的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分离,等到实际需要时再异步加载,通过loader转换,任何形式的资源都可以当做模块,比如CommonsJS,AMD,ES6,CSS,JSON,CoffeeScript,LESS等
伴随着移动互联网的大潮,当今越来越多的网站已经从网页模式进化到了WebApp模式。他们运行在现代浏览器里,使用HTML5,CSS3,ES6等新的技术来开发丰富的功能,网页不仅仅是完成浏览器的基本需求,WebApp通常是一个SPA(单页面应用),每一个视图通过异步的方式加载,这导致页面初始化和使用过程中会加载越来越多的JS代码,这给前端的开发流程和资源组织带来了巨大挑战
前端开发和其他开发工作的主要区别,首先是前端基于多语言、多层次的编码和组织工作,其次前端产品的交付是基于浏览器的,这些资源是通过增量加载的方式运行到浏览器端,如何在开发环境组织好这些碎片化的代码和资源,并且保证他们在浏览器端快速、优雅的加载和更新,就需要一个模块化系统,这个理想中的模块化系统是前端工程师多年来一直探索的难题
<script src=‘module.js‘></script>
服务端的NodeJS遵循CommonsJS规范,该规范核心思想是允许模块通过require方法来同步加载所需依赖的其他模块,然后通过exports或module.exports来导出需要暴露的接口
require(‘module‘);
exports.doStuff= function(){};
module.exports =someValue;
Asynchronous Module Definition 规范其实主要一个接口 define(id?,dependences?,factory)它要在声明模块的时候指定所有的依赖dependences,并且还要当作形参传到factory中,对于依赖的模块提前执行
define(‘module‘,[‘dep1‘,‘dep2‘],function(di,d2){
return someExportValue;
});
require([‘module‘,‘../file.js‘],function(module,file){});
Commons Module Definition
Webpack是一款模块加载器兼打包工具,它能把各种资源,如JS,JSX,ES6,SASS,LESS图片等都作为模块来处理和使用
安装:
cnpm install webpack -g
cnpm install webpack-cli -g
#测试
webpack -v
webpack-cli -v
创建webpack.config.js配置文件
创建项目(创建一个文件夹,用idea打开)
创建一个名为modules的目录,用于防止JS模块等资源文件
在modules下创建模块文件,如hello.js,用于编写JS模块相关代码
//暴露一个方法
exports.sayHi = function (){
document.write("<h1>明tian</h1>")
}
在modules下创建一个名为main.js的入口文件,用于打包时设置entry属性
var hello = require("./hello");
hello.sayHi();
在项目目录下创建webpack.config.js配置文件,使用webpack打包
module.exports = {
entry: ‘./modules/main.js‘,
output: {
filename: ‘./js/bundle.js‘
}
};
控制台 输入
webpack
打包成功 出现 ./dist/js/bundle.js
新建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>
这就是前端的模块化开发
Vue Router 是Vue.js是官方的路由管理器,它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌,包含的功能有:
基于第一个vue-cli进行测试学习,先查看node_modules中是否存贮vue-router
vue-router是一个插件包,所以我们还是需要用npm/cnpm来进行安装的,打开命令行工具,进入你的项目目录,输入下面命令
cnpm install vue-router --save-dev
引入VueRouter
// 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 VueRouter from ‘vue-router‘
Vue.config.productionTip = false
//显示声明使用VueRouter
Vue.use(VueRouter);
new Vue({
el: ‘#app‘,
components: { App },
template: ‘<App/>‘
})
./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
}
]
});
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‘ //自动扫描里面的路由配置
Vue.config.productionTip = false
new Vue({
el: ‘#app‘,
//配置路由
router,
components: { App },
template: ‘<App/>‘
})
App.vue
<template>
<div id="app">
<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.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>
<style scoped>
</style>
测试
cnpm run dev
# 进入工程目录
cd hello-vue
#安装vue-router
cnpm install vue-router --save-dev
#安装element-ui
cnpm i element-ui -S
#安装依赖
cnpm install
#安装SASS加载器
cnpm install sass-loader node-sass --save-dev
#启动测试
cnpm run dev
Npm命令解释·
npm install moduleName:安装模块到项目目录下
npm install -g moduleName:-g的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看npm config prefix的位置
npm install --save moduleName: --save的意思是将模块安装到项目目录下,并在package文件的dependences节点写入依赖,-S为该命令缩写
npm install --save-dev moduleName: --save-dev 的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
Login.vue
<template>
<div>
<!--el-form一个表单,两个输入框-->
<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>
<!--登陆按钮绑定了一个onSubmit事件-->
<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:‘‘
},
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){
/*如果引用成功了,会去router中push到main,这种方式称为编程式导航*/
this.$router.push("/main");
}else {
this.dialogVisible=true;
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({
routes: [
{
path: ‘/main‘,
component: Main
},{
path: ‘/login‘,
component: Login
}
]
});
main.js
import ElementUI from ‘element-ui‘;
/*需要加SASS*/
import ‘element-ui/lib/theme-chalk/index.css‘;
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
Vue.config.productionTip = false
Vue.use(router)
Vue.use(ElementUI);
new Vue({
el: ‘#app‘,
router,
/*给谁渲染*/
render: h => h(App),
})
测试
cnpm run dev
嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成,同样的,URL中各段动态路径也按某种结构对应嵌套的各层组件
List.vue
<template>
<h1>用户列表</h1>
</template>
<script>
export default {
name: "UserList"
}
</script>
<style scoped>
</style>
Profile.vue
<template>
<h1>个人信息</h1>
</template>
<script>
export default {
name: "UserProfile"
}
</script>
<style scoped>
</style>
Main.vue
<template>
<el-container style="height: 500px; border: 1px solid #eee">
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="[‘1‘, ‘3‘]">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-message"></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-menu"></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></router-view>
</el-main>
</el-container>
</el-container>
</template>
<style>
.el-header {
background-color: #b3c0d1;
color: #333;
line-height: 60px;
}
.el-aside {
color: #333;
}
</style>
<script>
export default {
data() {
const item = {
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄"
};
return {
tableData: Array(20).fill(item)
};
}
};
</script>
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,//嵌套路由
}
]
});
参数传递
Main.vue
<!--name传组件名,params传递参数 v-bind:绑定对象-->
<router-link :to="{name:‘UserProfile‘,params:{id:1}}">个人信息</router-link>
index.js
{
path:‘/user/profile/:id‘,
name:‘UserProfile‘,
component:UserProfile
},
List.vue
<template>
<div>
<h1>个人信息</h1>
{{$route.params.id}}
</div>
</template>
重定向
index.js
{
path:‘/goHome‘,
redirect:‘/main‘
}
main.vue
<el-menu-item index="1-3">
<router-link to="/goHome">回到首页</router-link>
</el-menu-item>
login.vue
this.$router.push("/main/"+this.form.username);
index.js (另一种传参数方式 props置为true)
path: ‘/main/:name‘,
props:true,
component: Main,
main.vue
<script>
export default {
props:[‘name‘],
name:‘Main‘
};
</script>
<span>{{name}}</span>
vue的辅助类VueRouter的路由模式有两种
我们可以通过修改路由配置实现两种模式的切换,代码以下:
export default new Router({
mode: ‘history‘,
routes: [
]
});
当用户请求路由文件中没有配置的路由规则的时候,我们应该将它转发/重定向到我们项目的404页面
创建一个404视图组件:NotFound.vue
<template>
<h2>404,您请求的页面走丢了</h2>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
12345678910111213
配置路由规则
{
path: "*",
component: NotFound
}
钩子就是我们前面说的vue生命周期中的钩子函数,路由钩子就是在请求对应的路由的时候,可以在请求到这个子组件之前添加一些自定义操作,在离开这个路由到的组件的时候做一些操作
路由钩子需要设置在我们需要设置设置它的子组件中,比如我们使用Profile.vue组件设置路由钩子
<template>
<div>
<h2>用户信息页</h2>
{{id}}---{{name}}
</div>
</template>
<script>
export default {
props: [‘id‘,‘name‘],
name: "profile",
beforeRouteEnter: (to,from,next)=>{
console.log("进入‘我的信息页‘之前"),
next()
},
beforeRouteLeave: (to,from,next)=>{
console.log("离开‘我的信息页‘之前")
next()
}
}
</script>
<style scoped>
</style>
参数说明
to:路由将要跳转的路径信息
from:路径跳转前的路径信息
next:路由的控制参数
我们应该将我们的异步请求和路由钩子合并起来使用,比如在加载用户信息页面的时候,我们将请求用户数据的异步请求放在beforeRouteEnter里去执行,这样用户在请求到页面的时候数据已经加载过来了,我们只需要将数据取出来渲染到视图组件上即可
安装axios
cnpm install -S axios
cnpm install -S vue-axios
main.js引用 Axios
import axios from ‘axios‘
import VueAxios from ‘vue-axios‘
Vue.use(VueAxios, axios)
在static文件夹(只有static文件夹下的资源才能直接请求到)下创建一个用于测试的JSON格式数据,首先创建一个名为mock的文件夹,开发中一般都将自己的测试用的假数据放在这个文件夹中;在这个文件夹中创建一个json格式的文件data.json
{
"name": "狂神说Java",
"url": "https://blog.kuangstudy.com",
"page": 1,
"isNonProfit": true,
"address": {
"street": "含光门",
"city": "陕西西安",
"country": "中国"
},
"links": [
{
"name": "bilibili",
"url": "https://space.bilibili.com/95256449"
},
{
"name": "狂伸说java",
"url": "https://blog.kuangstudy.com"
},
{
"name": "百度",
"url": "https://www.baidu.com/"
}
]
}
在Profile.vue中新增使用axios进行异步通信的方法
methods:{
getData:function () {
this.axios({
method:"get",
url:"http://localhost:8080/static/mock/data.json"
}).then(response=>console.log(this.info = response.data))
}
}
12345678
在beforeRouteEnter中调用这个方法
beforeRouteEnter: (to,from,next)=>{
console.log("进入‘我的信息页‘之前"),
next(vm => {
vm.getData();
});
},
将获取的数据渲染到数据模板上
<template>
<div>
<h2>用户信息页</h2>
{{id}}<br>
{{info.name}}---{{info.url}}---{{info.address}}
</div>
</template>
<script>
export default {
props: [‘id‘],
name: "profile",
data(){
return{
info:{
name: null,
url: null,
address: {
street: null,
city: null,
country: null
}
}
}
},
beforeRouteEnter: (to,from,next)=>{
console.log("进入‘我的信息页‘之前"),
next(vm => {
vm.getData();
});
},
beforeRouteLeave: (to,from,next)=>{
console.log("离开‘我的信息页‘之前")
next()
},
methods:{
getData:function () {
this.axios({
method:"get",
url:"http://localhost:8080/static/mock/data.json"
}).then(response=>console.log(this.info = response.data))
}
}
}
</script>
<style scoped>
</style>
原文:https://www.cnblogs.com/uxquan/p/14003926.html