Vue.js 基础
Vue 的哲学
- MVVM 架构:Model-View-ViewModel
- 事件驱动编程
# Node 和 Npm
# 安装与配置
nvm 安装
git clone -q --depth 1 --branch v0.40.8 https://github.com/nvm-sh/nvm.git ~/.nvm && echo "clone OK" && cat ~/.nvm/nvm.sh | head -3 >/dev/null; ls ~/.nvm/nvm.sh && bash -c 'export NVM_DIR="$HOME/.nvm"; . "$NVM_DIR/nvm.sh"; nvm --version'
环境变量
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
2
3
命令
nvm install 22 && nvm use 22 # 装/切版本
nvm alias default 22 # 设为默认(新终端生效)
nvm ls / nvm ls-remote
2
3
nodejs 配套的包管理工具(Node Package Manager),下载 nodejs 后自带
环境变量会自动配好,需要换一下源以避免未知 bug
国内源
- 淘宝:
https://registry.npmmirror.com/ - 腾讯云:
https://mirrors.cloud.tencent.com/npm/ - CNPM:
https://r.cnpmjs.org/
换源命令
#查询当前使用的镜像源
npm get registry
#设置为淘宝镜像源
npm config set registry https://registry.npmmirror.com/
#验证设置
npm get registry
#还原为官方源
npm config set registry https://registry.npmjs.org/
2
3
4
5
6
7
8
9
10
11
# 使用
创建模块,用以在当前文件夹生成一个新的 package.json 文件
npm init
安装模块
npm install <name># = npm i
- -g 全局安装
- -D 将安装在当前项目的 dependencies 模块
- --save-dev 将安装在 devDependencies 区,即开发模块
卸载模块
npm uninstall <name>
同样的,-g 卸载全局模块
查看已安装模块
npm ls
# 脚本执行
使用npm run命令执行脚本,脚本写在 package.json 的 scripts 字段,例如
{
"name": "northboat blog",
"version": "2.0.0",
"scripts": {
"dev": "export NODE_OPTIONS=--openssl-legacy-provider && node --max_old_space_size=4096 ./node_modules/vuepress/cli.js dev docs",
"build": "export NODE_OPTIONS=--openssl-legacy-provider && node --max_old_space_size=4096 ./node_modules/vuepress/cli.js build docs",
"dev:win": "set NODE_OPTIONS=--openssl-legacy-provider && node --max_old_space_size=4096 ./node_modules/vuepress/cli.js dev docs",
"build:win": "set NODE_OPTIONS=--openssl-legacy-provider && node --max_old_space_size=4096 ./node_modules/vuepress/cli.js build docs",
"predev": "node utils/check.js dev && vdoing",
"prebuild": "node utils/check.js build && ./vdoing/bin/checkVersion.js",
},
"license": "MIT",
"devDependencies": {
"i": "^0.3.7",
"json2yaml": "^1.1.0",
"npm": "^11.0.0",
"vuepress": "1.9.9",
"vuepress-theme-vdoing": "^1.12.9",
"yamljs": "^0.3.0"
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
执行
npm run build:win
相当于执行
set NODE_OPTIONS=--openssl-legacy-provider && node --max_old_space_size=4096 ./node_modules/vuepress/cli.js build docs
# Vue 基础
# 第一个 Vue 程序
七大对象,
el、data、methods、computed、template、render、watch
cdn引入
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
首个vue页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
{{message}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, Vue!"
}
});
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
绑定,其中data即为Model(数据)
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, Vue!"
}
});
</script>
2
3
4
5
6
7
8
取值:所谓View层
<div id="app">{{message}}</div>
双向绑定,在控制台直接修改data值,将动态打印message,所谓View-Model
vm.message = "hahaha"
# 基础语法
用指令绑定事件
# v-bind
v-bind:绑定,直接使用el中的data,用双引号引入
<span v-bind:title="message">鼠标悬停显示提示信息</span>
绑定组件
<div id="app">
<my-item v-for="node in list" v-bind:item="node"></my-item>
</div>
<script>
Vue.component("my-item", {
props: ['item'],
template: '<li>{{item}}</li>'
})
var vue = new Vue({
el: "#app",
data: {
list: ["hahaha", "sad", "northboat"]
},
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# v-if
v-if/v-else
<h1 v-if="ok">{{yes}}</h1>
<h1 v-else>{{no}}</h1>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, Vue!",
ok: true,
yes: "Yes~",
no: "No~"
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
在控制台修改
vm.ok = false
页面将打印No~
v-else-if
<h1 v-if="type==='A'">A</h1>
<h1 v-else-if="type==='B'">B</h1>
<h1 v-else>other type</h1>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, Vue!",
type: 'A'
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
通过在前端修改vm.type,可以动态修改页面内容
# v-for
v-for展示
<li v-for="hahaha in items">{{hahaha.message}}</li>
在data中定义数组,用[]定义数组
<script>
var vm = new Vue({
el: "#app",
data: {
items: [
{message: "java"},
{message: "vue"},
],
}
});
</script>
2
3
4
5
6
7
8
9
10
11
传入两种参数v-for="(hahaha, index) in items"其中index为数组中元素下标,hahaha为数组元素
<li v-for="(hahaha, index) in items">{{index}} : {{hahaha.message}}</li>
在控制台里,输入 app.items.push({ message: '新项目' }),动态增加元素
# v-on
添加事件监听
<div>
<p>{{message}}</p>
<button v-on:click="reverseMsg">反转message</button>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, Vue!",
},
methods: {
reverseMsg: function(){
this.message = this.message.split('').reverse().join('');
}
},
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# v-model
实现双向绑定,灰常重要
model:信息,实现实时更新信息
可作用于input.type = text\textarea\radio,注意radio用同样的name绑定在一起
<p>{{inputMsg}}</p>
<input v-model="inputMsg" type="text">
<script>
var vm = new Vue({
el: "#app",
data: {
inputMsg: "wdnmd",
}
});
</script>
2
3
4
5
6
7
8
9
10
11
在input中输入的信息将实时更新到<p></p>中
<input type="radio" name="gender" value="男" v-model="gender">男
<input type="radio" name="gender" value="女" v-model="gender">女
<input type="radio" name="gender" value="男酮" v-model="gender">♂
<h3>你选中了:{{gender}}</h3>
<script>
var v = new Vue({
el: "#app",
data: {
gender: '',
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
下拉框:select,用v-modle进行初始化,在script中赋值
<select v-model="grade">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<h3>评级:{{grade}}</h3>
<script>
var v = new Vue({
el: "#app",
data: {
msg: "nmsl",
gender: '',
grade: 'A'
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
一般会这样处理,留一个disable的下拉框提示用户请选择
<select v-model="grade">
<option value="" disabled>--请选择--</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<h3>评级:{{grade}}</h3>
<script>
var v = new Vue({
el: "#app",
data: {
msg: "nmsl",
gender: '',
grade: ''
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- v-model的优先级高于value、checked、selected,直接从js中拿数据
# 组件
# 自定义标签
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="app">
<my-item v-for="node in list" v-bind:item="node"></my-item>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
Vue.component("my-item", {
props: ['item'],
template: '<li>{{item}}</li>'
})
var vue = new Vue({
el: "#app",
data: {
list: ["hahaha", "sad", "northboat"]
}
});
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 插槽
slot
<div id="app">
<test>
<!-- v-bind简写为 : v-on简写为 @click -->
<!-- 绑定插槽,绑定数据 -->
<test-title slot="t" :title="hahaha"></test-title>
<test-items slot="is" v-for="i in items" :item="i"></test-items>
</test>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
Vue.component("test", {
// 设置插槽名字,用于以外元素绑定插槽
template: '<div>\
<slot name="t"></slot>\
<ul>\
<slot name="is"></slot>\
</ul>\
</div>'
});
Vue.component("test-title", {
props: ["title"],
template: '<h3>{{title}}</h3>'
});
Vue.component("test-items", {
props: ["item"],
template: '<li>{{item}}</li>'
})
var v = new Vue({
el: "#app",
data: {
hahaha: "NorthBoat",
items: ["java", "vue", "bootstrap"],
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
定义插槽
Vue.component("test", {
// 设置插槽名字,用于以外元素绑定插槽
template: '<div>\
<slot name="t"></slot>\
<ul>\
<slot name="is"></slot>\
</ul>\
</div>'
});
2
3
4
5
6
7
8
9
设置插槽名字,用于外来元素绑定插槽
<slot name="t"></slot>
绑定插槽,绑定数据
:title="hahaha"绑定的是test-title:title,即当前组件的pros,slot="t"是将当前组件与插槽t绑定,实现自定义数据、组件动态交互
<test>
<!-- 绑定插槽,绑定数据 -->
<test-title slot="t" :title="hahaha"></test-title>
<test-items slot="is" v-for="i in items" :item="i"></test-items>
</test>
2
3
4
5
- v-bind简写
: - v-on简写
@
Vue.component("test-title", {
props: ["title"],
template: '<h3>{{title}}</h3>'
});
Vue.component("test-items", {
props: ["item"],
template: '<li>{{item}}</li>'
})
var v = new Vue({
el: "#app",
data: {
hahaha: "NorthBoat",
items: ["java", "vue", "bootstrap"],
}
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 自定义事件分发
设置组件
//div、slot
Vue.component("test", {
// 设置插槽名字,用于以外元素绑定插槽
template: '<div><slot name="t"></slot><ul><slot name="is"></slot></ul></div>'
});
//title
Vue.component("test-title", {
props: ["title"],
template: '<h3>{{title}}</h3>'
});
2
3
4
5
6
7
8
9
10
11
定义方法,与外界方法进行绑定
//li
Vue.component("test-items", {
props: ["item", "index"],
template: '<li>{{item}}<button @click="remove">删除</button></li>',
methods:{
remove: function(index){
this.$emit("remove", index)
}
}
})
2
3
4
5
6
7
8
9
10
定义vue对象
var v = new Vue({
el: "#app",
data: {
hahaha: "NorthBoat",
items: ["java", "vue", "bootstrap"],
},
methods: {
removeItem: function(index){
this.items.splice(index, 1);
}
}
});
2
3
4
5
6
7
8
9
10
11
12
进行一系列绑定
- 标签与插槽绑定
- 插槽中props与data数据进行绑定,可以多个(
v-for遍历出来的数据可以为(data, index)的形式) - 插槽中方法与vue对象中方法进行绑定,这一步需要绑定三次,一次在body的标签中,一次在插槽的方法里用emit绑定,一次在插槽template中绑定插槽的方法
<div id="app">
<test>
<!-- v-bind简写为: v-on简写为@ -->
<!-- 绑定插槽,绑定数据 -->
<test-title slot="t" :title="hahaha"></test-title>
<test-items slot="is" v-for="(item,index) in items" :item="item" :index="index" @remove="removeItem"></test-items>
</test>
</div>
2
3
4
5
6
7
8
# 网络通信
Axios:整合jQuery.ajax实现网络通信,异步通信
在钩子函数中实现资源加载功能,如重写mounted(),请求回的数据用data()函数接收,存于return的变量中,如以下代码存于info,在view层直接用info取数据
<div id="app">
{{info.name}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var v = new Vue({
el: "#app",
data(){
return{
info:{
name: null,
}
}
},
mounted(){
axios.get("data.json").then(response=>{this.info = response.data});
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
post方法
mounted(){
axios.post("39.106.160.174:8084/getMainPage").then(response=>{this.info = response.data});
}
2
3
# 计算属性
重写vue的computed属性
与methods的区别
- 通过computed返回的值将储存在内存中,如以下代码Date.now()将储存在getTimeVal中,我们可以直接通过getTimeVal进行变量取值
- 而methods只作用一次,并不储存
<div id="app">
<h3>currentTimeByMethod:{{getTime()}}</h3>
<h3>currentTimeByValue:{{getTimeVal}}</h3>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
var v = new Vue({
el: "#app",
methods: {
getTime: function(){
return Date.now();
}
},
computed: {
getTimeVal: function(){
return Date.now();
}
}
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Vue-Cli 脚手架
npm 类似于 maven
下载 vue-cli
cnpm install vue-cli -g
# Vue-Cli 程序
初始化
vue init webpack myvue //myvue项目名
cd myvue
npm install //根据myvue目录下package.json安装依赖
npm run dev //运行项目
2
3
4
5
6
依赖都放在node_modules目录下,相当于java的lib
一个问题:在 vscode 终端中运行npm run dev报错无法在此系统运行脚本,需要在管理员权限的windows powershell中将执行策略设置为RemoteSigned
set-ExecutionPolicy RemoteSigned
查看是否更改成功(所有东西都变成了组件)
get-ExecutionPolicy
端口号在config/index.js中配置
# Webpack 打包
服务器端的 nodejs 遵循 CommonsJS 规范,该规范的核心思想是允许模块通过 require 方法来同步加载所需以来的其他模块,然后通过 exports 来导出需要暴露的接口
require("module");
require("../module.js");
export.doStuff = function(){};
module.exports = someValue;
2
3
4
限定了作用域,防止项目中不同 js 的重名冲突,但同步 → 阻塞
- AMD(Asynchronous Module Definition)异步加载模块
- CMD(Commons Module Definition)规范和 AMD 类似,但尽量保持简单 → sea.js
ES6 规范:模块化思想
import "jquery";
export function doStuff(){};
module "localModule"{};
2
3
静态模块打包器,它会递归的构造一个依赖关系图(dependency graph),将 ES6 规范的代码打包降级为 ES5 规范给浏览器使用
安装 webpack
npm install webpack -g
npm install webpack-cli -g
2
查看安装
webpack -v
webpack-cli -v
2
配置 webpack.config.js 文件
- entry:入口文件,main.js
- output:输出,指定webpack把处理后的文件放置在指定目录
- module:模块,用于处理各种类型的文件
- plugins:插件,如热更新、代码重用等
- resolve:设置路径指向
- watch:监听,用于设置文件改动后直接打包
webpack 实践,新建空项目
- modules:放置 js 文件
- webpack.config.js:webpack 打包配置文件
- index.html:展示页面
编写 hello.js
//暴露一个方法
exports.sayHey = function(){
document.write("<h1>ES6规范</h1>");
}
2
3
4
main.js
var hello = require("./hello");
hello.sayHey();
2
使用webpack命令打包,生成 ES5 规范的一个统一的 js 文件(压缩过的)
webpack.config.js
module.exports = {
entry: "./modules/main.js",
output: {
filename: "./js/bundle.js"
}
};
2
3
4
5
6
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./dist/js/bundle.js"></script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
点开 html 即会在网页上打印一个<h1>ES6规范</h1>
# Router 路由
路由,控制页面跳转
在 vscode 中使用 vueter 插件敲
<vue>+tab可以自动补全 vue 文件模板
新建组件:以下 vue 文件均放在组件目录下
NorthBoat.vue
<template>
<h1>NorthBoat</h1>
</template>
<script>
export default {
name: "NorthBoat"
}
</script>
<style>
</style>
2
3
4
5
6
7
8
9
10
11
12
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style scoped>中 scoped 限制样式作用域仅为当前 vue 文件
安装 router:在当前项目下安装vue-router
npm install vue-router --save-dev
配置 router:新建 router 目录,新建 index.js 为 router 配置文件
- 导入组件
import Vue from 'vue'
import Router from 'vue-router'
import Content from '../components/Content'
import Main from '../components/Main'
import NorthBoat from '../components/NorthBoat'
2
3
4
5
- 安装路由
import Router from 'vue-router'
Vue.use(Router);
2
- 配置路由
export default new Router({
routes:[
{
//路由路径
path: "/content",
//跳转组件
component: Content,
name: "content"
},
{
path: "/main",
component: Main,
name: "main"
},
{
path: "/home",
//跳转组件
component: NorthBoat,
name: "home"
},
]
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
注入 router:在 main.js 中导入路由目录
import router from './router' //将自动扫描目录下的路由
在 Vue 对象中注入路由
new Vue({
el: '#app',
//配置路由
router: router,
components: { App },
template: '<App/>'
})
2
3
4
5
6
7
使用 router:在 App.vue 中使用 router 进行跳转
<template>
<div id="app">
<h1>Vue-Router</h1>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<router-link to="/home">home页</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>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
其中
router-link为链接,相当于<a></a>;to为跳转页面,相当于`@RequestMapper``- ``router-view
为展示跳转内容,即在`之下以一个组件的形式展示跳转页内容
导入 axios
npm install --save axios vue-axios
import axios from 'axios'
import vueAxios from 'vue-axios'
Vue.use(axios, vueAxios);
2
3
# Element-UI
网站快速成型工具,类似于bootstrap
# Element-UI 基础
新建项目
vue init webpack hello-element-ui
安装 element-ui
npm i element-ui -S
安装 router、sass 加载器(element-ui 中用到了 sass)
npm install vue-router --save-dev
npm install sass-loader node-sass --save-dev
2
写一个简单的登录界面
- 编写组件,暴露接口
- 引入接口,编写路由
- 将路由、ElementUI注入main.js
编写组件 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>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Main.vue
<template>
<h1>NorthBoat</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
App.vue
<template>
<div id="app">
<h1>hahaha</h1>
<router-link to="/login">登录</router-link>
<router-link to="/main">主页</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>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
配置路由
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
}
]
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
路由注入 main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
Vue.use(router);
new Vue({
el: '#app',
router: router,
render: h => h(App) //ElementUI
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
遇到了 sass-loader、node-sass、nodejs 版本降级问题:Module build failed: Error: Node Sass version 7.0.0 is incompatible with ^4.0.0.@node-sass版本问题解决总汇 (opens new window)
# 路由嵌套及重定向
使用
children进行路由嵌套
在 index.js 中进行路由嵌套
import Vue from 'vue'
import Router from 'vue-router'
import Main from '../views/Main'
import UserList from '../views/user/List'
import UserProfile from '../views/user/Profile'
Vue.use(Router);
export default new Router({
mode: 'history',
routes:[
{
path: '/main',
component: Main,
children:[
{path: '/user/profile', component: UserProfile},
{path: '/user/list', component: UserList}
]
}
]
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
引入 vue,在 route.children 属性中定义重定向页面
mode: 'history'用于去除网页的#号
重定向,直接在 index.js 中进行路由的重定向,以下 js 将/重定向到/login页,当访问/时自动跳转到/login
routes:[
{
path: '/',
redirect: '/login'
}
]
2
3
4
5
6
引入 404,编写NotFound.vue,在 index.js 中引入,定义路由
import NotFound from '../views/NotFound'
Vue.use(Router);
export default new Router({
routes:[
{
path: '/*',
component: NotFound
}
]
});
2
3
4
5
6
7
8
9
10
注意:路由是按照上下次序进行检索,你应将所有有用的路由定义在/*上方,否则会直接跳到404页面
# 参数传递
template,其中name为路由的名字,在 index.js 中唯一定义
<el-menu-item-group>
<router-link :to="{name: 'Profile', params: {username: 'NorthBoat'}}"><el-menu-item index="1-1">个人信息</el-menu-item></router-link>
<router-link :to="{name: 'List', params: {id: 4}}"><el-menu-item index="1-2">用户列表</el-menu-item></router-link>
</el-menu-item-group>
2
3
4
index.js,profile 可以理解为 get,在 url 后通过/:key的形式传入参数;list 可以理解为 post,通过 props 传参,要在 index.js 中令该 route 的 props 为 true
export default new Router({
mode: 'history',
routes:[
{
path: '/main',
component: Main,
props: true,
children:[
{path: '/user/profile/:username', component: UserProfile, name: 'Profile'},
{path: '/user/list', component: UserList, name: 'List', props: true}
]
},
]
})
2
3
4
5
6
7
8
9
10
11
12
13
14
Profile.vue,直接通过 route 对象拿到参数
<template>
<h1>{{$route.params.username}}</h1>
</template>
<script>
export default {
name: "Profile"
}
</script>
<style>
</style>
2
3
4
5
6
7
8
9
10
11
12
List.vue,通过 props 接收参数,再从 props 中拿取参数
<template>
<h1>{{id}}</h1>
</template>
<script>
export default {
props:['id'],
name: "List"
}
</script>
<style>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
# 钩子函数及 Axios
# beforeRouteEnter
在进入路由前
常从某一路由拿取数据,可以通过data()的方式将数据保存在当前页面
data(){
return{
info:{
name: null,
id: -1,
pwd: null
}
}
},
methods: {
getData: function(){
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(response => {this.info = response.data});
}
},
beforeRouteEnter: (to, from, next)=>{
console.log("进入路由之前");
next(vm => {
vm.getData();
})
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- 在vue中,静态数据通常放置在
/static/mock/目录下
next() 的几种用法:
- next():直接跳转到下一页面,如,若是
beforeRouteEnter,则为进入当前页;若是beforeRouteLeave,则为进入跳转页面 - next(false):回到上一页面,从哪来回哪去
- next(vm => {}):只能在
beforeRouteEnter中使用,vm为当前vue对象,可以调用其中一些方法,然后进入当前页面
# beforeRouteLeave
与上相同,通常用于将参数传递到下一页面,注意作用时间
# 引入 Vue 组件
在MyNav.vue、MySidebar.vue中导出
在 Main.vue 的 script 中导入
<script>
import MyNav from './MyNav.vue'
import MySidebar from './MySidebar.vue'
export default {
name: "Main",
components: { MyNav, MySidebar }
}
</script>
2
3
4
5
6
7
8
9
在 Main.vue 的 template 中使用
<template>
<div>
<my-nav id="nav"></my-nav>
<my-sidebar id="sidebar"></my-sidebar>
<router-view></router-view>
</div>
</template>
2
3
4
5
6
7
更多玩儿法