vue
vue简介
Vue是一套用于构建用户界面的渐进式JavaScript框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,方便与第三方库或既有项目整合。
Soc原则:关注点分离原则
视图层:HTML+CSS+JS,给用户看,刷新后台给的数据
网络通信:axios
网页跳转:vue-router
状态管理:vuex
Vue-UI:https://ice.work/
javascript框架
1.vue
特色:计算属性,综合了虚拟DOM和模块化
核心:组件化和数据驱动
v-on:绑定时间,简写@
v-model:数据双向绑定
v-bind:给组件绑定参数,简写:
v-if
slot:插槽
this.$emit(“事件名”,参数)
虚拟DOM:把DOM操作放到內存中执行
https://panjiachen.github.io/vue-element-admin-site/zh/
2.axios
前端通信框架
3.Angular
4.React
MVVM
什么是MVVM?
MVVM (Model-View-ViewModel) 是一种软件架构设计模式,由微软WPF (用于替代WinForm,以前就是用这个技术开发桌面应用程序的)和Silverlight (类似于Java Applet,简单点说就是在浏览器上运行的WPF)的架构师Ken Cooper和Ted Peters 开发,是一种简化用户界面的事件驱动编程方式。由John Gossman (同样也是WPF和Silverlight的架构师)于2005年在他的博客上发表。
MVVM源自于经典的MVC (ModIe-View-Controller) 模式。MVVM的核心是ViewModel层,负责转换Model中的数据对象来让数据变得更容易管理和使用,其作用如下:
该层向上与视图层进行双向数据绑定
向下与Model层通过接口请求进行数据交互
第一个vue例子:(清楚了解MVVC)
不是vue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
<span v-bind:title="message">
鼠标悬停几秒钟查看此处动态绑定的提示信息!
</span>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el:"#app",
data:{
message:"hello,vue"
}
});
</script>
</body>
</html>
v-bind等被称为指令。指令带有前缀v以表示它们是Vue提供的特殊特性。可能你已经猜到了, 它们会在渲染的DOM上应用特殊的响应式行为在这里,该指令的意思是:“将这个元素节点的title特性和Vue实例的message属性保持一致”。
判断
<!--view层-->
<div id="app">
<h1 v-if="type==='A'">A</h1>
<h1 v-else-if="type==='B'">B</h1>
<h1 v-else>C</h1>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el:"#app",
data: {
type: 'A'
}
});
</script>
循环
<!--view层-->
<div id="app">
<li v-for="item in items">
{{item.massage}}
</li>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el:"#app",
data: {
items: [
{massage: 'pcy'},
{massage: 'pcy1'}
]
}
});
</script>
事件
<!--view层-->
<div id="app">
<button v-on:click="sayHi">click</button>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el:"#app",
data:{
message:"hello,vue"
},
methods: {//method必须定义在Vue的method对象中
sayHi: function () {
alert(this.message);
}
}
});
</script>
表单绑定事件
<!--view层-->
<div id="app">
输入的文本:<input type="text" v-model="message">{{message}}</input></br>
输入的文本:<textarea type="text" v-model="message"></textarea>{{message}}</br>
<input type="radio" name="sex" value="男" v-model="pcy">男
<input type="radio" name="sex" value="女" v-model="pcy">女
<p>
选中了:{{pcy}}
</p>
下拉框:
<select v-model="selected">
<option value="" >----请选择-----</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
value:{{selected}}
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el:"#app",
data:{
message: "hello,vue",
pcy: '',
selected: ''
}
});
</script>
Vue组件
组件:自定义一个标签
<div id="app">
<pcy></pcy>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
//定义一个vue组件
Vue.component("pcy",{
template: '<li>hello</li>'
});
var vm=new Vue({
el:"#app",
data:{
message: "hello,vue",
pcy: '',
selected: ''
}
});
</script>
<div id="app">
<!--组件:传递给组件中的值,props-->
<pcy v-for="item in items" v-bind:t="item"></pcy>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
//定义一个vue组件
Vue.component("pcy",{
props: ['t'],
template: '<li>{{t}}</li>'
});
var vm=new Vue({
el:"#app",
data:{
items: ["java","linux"]
}
});
</script>
网络通信(Axios)
网络通信
jQuery
什么是Axios
Axios是一个开源的可以用在浏览器端和Node JS的异步通信框架, 它的作用就是实现AJAX异步通信,其功能特点如下:
从浏览器中创建XMLHttpRequests
从node.js创建http请求
支持Promise API[JS中链式编程]
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换JSON数据
客户端支持防御XSRF(跨站请求伪造)
GitHub:https://github.com/axios/axios
中文文档:http://www.axios-js.com/
第一个实例:
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/"
}
]
}
demo7.html
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--v-clock 解决闪烁问题-->
<style>
[v-clock]{
display: none;
}
</style>
<div id="vue" v-clock>
<div>{{info.name}}</div>
<div>{{info.address.street}}</div>
<a v-bind:href="info.url">点我</a>
</div>
<!--导入vue.js-->
<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el: '#vue',
data() {
//data:属性:vm
return{
info:{
name: null,
address: {
street: null,
city: null,
country: null
},
url: null
}
}
},
mounted(){
//钩子函数,列式编程
axios.get('../data.json').then(response=>(this.info=response.data))
}
});
</script>
</body>
</html>
计算属性
定义:计算出来的结果保存在属性当中,內存运行:虚拟Dom
计算属性可以想象为缓存
实例:
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--v-clock 解决闪烁问题-->
<div id="vue" v-clock>
<p>currentTime1:{{currentTime1()}}}</p>
<p>currentTime2:{{currentTime2}}}</p>
</div>
<!--导入vue.js-->
<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
var vm=new Vue({
el: '#vue',
data: {
message: 'hello'
},
methods: {
currentTime1: function () {
return Date.now();
}
},
computed: {
currentTime2: function () {
this.message;
return Date.now();
}
}
});
</script>
</body>
</html>
插槽(slot)
例子:
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--v-clock 解决闪烁问题-->
<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>
<!--导入vue.js-->
<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
//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']
}
});
</script>
</body>
</html>
自定义内容分发
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--v-clock 解决闪烁问题-->
<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" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
<!--导入vue.js-->
<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--model:数据-->
<script>
//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>{{item}}<button @click="remove">删除</button></li>',
methods: {
remove: function (index) {
//自定义事件分发
this.$emit('remove',index);
}
}
});
var vm=new Vue({
el: '#vue',
data: {
title: '秦老师',
todoItems: ['狂神说','狂神说java']
},
methods: {
removeItems: function (index) {
this.todoItems.splice(index,1)
}
}
});
</script>
</body>
</html>
第一个vue-cli项目
1. 什么是vue-cli
vue-cli 官方提供的一个脚手架,用于快速生成一个 vue 的项目模板;
预先定义好的目录结构及基础代码,就好比咱们在创建 Maven 项目时可以选择创建一个骨架项目,这个骨架项目就是脚手架,我们的开发更加的快速;
2.安装node.js
1.查看版本
where node 查看node安装目录
node -v
npm -v npm,就是一个软件包管理工具
2.安装Node.js淘宝镜像加速器(cnpm)
# -g 就是全局安装
npm install cnpm -g
安装的位置在:C:\Users\pcy\AppData\Roaming\npm
3.安装vue-cli
cnpm instal1 vue-cli -g
#测试是否安装成功
#查看可以基于哪些模板创建vue应用程序,通常我们选择webpack
vue list
4.创建第一个vue程序
1.创建一个基于webpack模板的vue应用程序
#1、首先需要进入到对应的目录 D:\Desktop\学习流程\代码
#2、这里的myvue是顶日名称,可以根据自己的需求起名
vue init webpack myvue
2.初始化并运行
cd myvue
npm install
npm run dev
出现问题的时候可以有提示,直接处理
什么是Webpack
本质上javaScript应用程序的静态资源模块打包器。当webpack处理应用程序时,他会构建一个依赖关系图,其中包含应用程序需要的每一个模块。然后将所有这些模块打包成一个或多个bundle.
相当于后端的maven
WebPack是一款模块加载器兼打包工具, 它能把各种资源, 如JS、JSX、ES 6、SASS、LESS、图片等都作为模块来处理和使用。
npm install webpack -g
npm install webpack-cli -g
测试安装成功: 输入以下命令有版本号输出即为安装成功
webpack -v
webpack-cli -v
使用webpack
hello.js
//暴露一个方法
exports.sayHi = function () {
document.write("<h1>狂神</h1>")
}
main.js
var hello = require("./hello");
hello.sayHi();
webpack.config.js
module.exports = {
//程序的入口
entry : './modules/main.js',
//导出的文件位置
output : {
filename : './js/bundle.js'
}
}
执行webpack后导出一个文件
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>
用webpack --watch监听webpack变化
vue-router路由
Vue Router是Vue.js官方的路由管理器(路径跳转)。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的CSS class的链接
1. 安装
基于第一个vue-cli进行测试学习;先查看node_modules中是否存在 vue-router
vue-router 是一个插件包,所以我们还是需要用 npm/cnpm 来进行安装的。打开命令行工具,进入你的项目目录,输入下面命令。
npm install vue-router --save-dev
npm run dev
实例:
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
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">
<router-link to="./main">首页</router-link>
<router-link to="./content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<script>
import Content from './components/Content'
export default {
name: 'App',
components: {
Content
}
}
</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
// 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
Vue.use(router);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
vue+Element
1.创建一个hello-vue
vue init webpack hello-vue
2.安装依赖,我们需要安装 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 加载器
cnpm install sass-loader node-sass --save-dev
# 启动测试
npm run dev
Npm命令解释
npm install moduleName:安装模块到项目目录下
npm install -g moduleName:-g 的意思是将模块安装到全局,具体安装到磁盘的哪个位置,要看 npm config prefix的位置
npm install moduleName -save:–save的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖,-S为该命令的缩写
npm install moduleName -save-dev:–save-dev的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写
报错:
Module build failed: TypeError: this.getOptions is not a function
at Object.loader (D:\Desktop\学习流程\代码\hello-vue\node_modules\_sass-loader@11.0.1@sass-loader\dist\index.js:25:24)
版本太高了
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
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>
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../views/Main'
import Login from '../views/Login'
Vue.use(VueRouter);
export default new VueRouter({
routes: [
{
path :'/main',
component: Main
},
{
path :'/login',
component: Login
}
]
});
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'
//导入elementUI
import ElementUI from "element-ui"
//导入element css
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(router)
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render : h => h(App)
});
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>
快速安装一个 网页的网站
https://docsify.js.org/#/quickstart
嵌套路由
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>
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>
index.js
import Vue from 'vue'
import VueRouter 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(VueRouter);
export default new VueRouter({
routes: [
{
path :'/main',
component: Main,
children: [
{path: '/user/profile',component: UserProfile},
{path: '/user/list',component: UserList}
]
},
{
path :'/login',
component: Login
}
]
});
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'
//导入elementUI
import ElementUI from "element-ui"
//导入element css
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(router)
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render : h => h(App)
});
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>
list.vue
<template>
<h1>用户列表</h1>
</template>
<script>
export default {
name: "UserList"
}
</script>
<style scoped>
</style>
Profile.vue
<template>
<!--所有的元素必须不能直接放在根节点下-->
<div>
<h1>个人信息</h1>
</div>
</template>
<script>
export default {
name: "UserProfile"
}
</script>
<style scoped>
</style>
传递参数以及重定向
参数传递
Main.vue
<!--name:传组件名 params:传递参数,需要绑定对象-->
<router-link v-bind:to="{name: 'UserProfile',params: {id: 1}}">个人信息</router-link>
Profile.vue
<template>
<!--所有的元素必须不能直接放在根节点下-->
<div>
<h1>个人信息</h1>
{{id}}
<!--{{$route.params.id}}-->
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile"
}
</script>
<style scoped>
</style>
index.js
//props:支持传递参数
children: [
{path: '/user/profile/:id',
name: 'UserProfile',
component: UserProfile,
props: true
},
重定向页面
Main.vue
<el-menu-item index="1-3">
<!--插入的地方-->
<router-link to="/goHome">返回首页</router-link>
</el-menu-item>
index.js
children: [
{path: '/user/profile/:id',
name: 'UserProfile',
component: UserProfile,
props: true
},
{path: '/user/list',component: UserList},
{
path: '/goHome',
redirect: '/main'
}
]
第二个例子:
login.vue
methods: {
onSubmit(formName) {
// 为表单绑定验证功能
this.$refs[formName].validate((valid) => {
if (valid) {
// 使用 vue-router 路由到指定页面,该方式称之为编程式导航
this.$router.push("/main/"+this.form.username);
} else {
this.dialogVisible = true;
return false;
}
});
}
}
}
Main.vue
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>{{name}}</span>
</el-header>
<el-main>
<!--在这里展示视图-->
<router-view />
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
props: ['name'],
name: "Main"
}
index.js
routes: [
{
//props:支持传递参数
path :'/main/:name',
component: Main,
props: true,
路由钩子与404
路由模式
路由模式有两种
- hash:路径带 # 符号,如 http://localhost:8080/#/login
- history:路径不带 # 符号,如 http://localhost:8080/login
第二种:
export default new VueRouter({
mode: 'history',
routes: [
]
404页面
NotFound.vue
<template>
<h1>404,你的页面走丢了</h1>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
index.js
import Vue from 'vue'
import VueRouter 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'
import NotFound from '../views/NotFound'
Vue.use(VueRouter);
export default new VueRouter({
mode: 'history',
routes: [
{
//props:支持传递参数
path :'/main/:name',
component: Main,
props: true,
children: [
{path: '/user/profile/:id',
name: 'UserProfile',
component: UserProfile,
props: true
},
{path: '/user/list',component: UserList},
{
path: '/goHome',
redirect: '/main'
}
]
},
{
path :'/login',
component: Login
},
{
path :'*',
component: NotFound
}
]
});
路由钩子
静态数据从static文件夹中使用
beforeRouteEnter
:在进入路由前执行
beforeRouteLeave
:在离开路由前执行
参数说明:
to:路由将要跳转的路径信息
from:路径跳转前的路径信息
next:路由的控制参数
next() 跳入下一个页面
next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
next(false) 返回原来的页面
next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例
使用异步请求
1.安装 Axios
npm install --save vue-axios
只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。
profile.vue
<template>
<!--所有的元素必须不能直接放在根节点下-->
<div>
<h1>个人信息</h1>
{{id}}
<!--{{$route.params.id}}-->
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile",
//钩子函数 过滤器
beforeRouteEnter: (to, from, next) => {
//加载数据
console.log("进入路由之前")
// next(vm => {
// //进入路由之前执行getData方法
// vm.getData()
// });
},
beforeRouteLeave: (to, from, next) => {
console.log("离开路由之后")
next();
},
//axios
methods: {
getData: function () {
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (response) {
console.log(response)
})
}
}
}
</script>
<style scoped>
</style>
main.js-*/
import vueAxios from 'vue-axios'
import axios from 'axios'
Vue.use(axios,vueAxios)