wordpress会员制网站,wordpress网站主修改,黑龙江省建设工程招标网站,网站界面设计方案vue echarts 快速入门 本案例即有nodejs和vue的基础#xff0c;又在vue的基础上整合了echarts Nodejs基础
1、Node简介
1.1、为什么学习Nodejs(了解) 轻量级、高性能、可伸缩web服务器前后端JavaScript同构开发简洁高效的前端工程化 1.2、Nodejs能做什么(了解) Node 打破了…vue echarts 快速入门 本案例即有nodejs和vue的基础又在vue的基础上整合了echarts Nodejs基础
1、Node简介
1.1、为什么学习Nodejs(了解) 轻量级、高性能、可伸缩web服务器前后端JavaScript同构开发简洁高效的前端工程化 1.2、Nodejs能做什么(了解) Node 打破了过去 JavaScript 只能在浏览器中运行的局面。前后端编程环境统一大大降低了前后端语言切换的代价。以下是Node可以实现的工作仅作了解 Web 服务器命令行工具网络爬虫桌面应用程序开发app嵌入式游戏… 1.3、Node是什么 Node.js®是基于 Chrome的V8 JavaScript 引擎构建的JavaScript运行环境。 Node.js不是新语言也不是一个框架或者一个库而是一个软件。 Node.js是一个 JavaScript 运行环境 说白了就是用来运行js的。 官网https://nodejs.org/en/ 中文官网https://nodejs.org/zh-cn/ 1.4、Nodejs架构和运行过程 1.4.1、Natives modules 当前内容用JavaScript实现提供应用程序可以直接调用的模块例如 fs、path、http等JavaScript无法直接操作底层硬件 1.4.2、Builtin modules 胶水层
1.4.3、底层 V8执行JavaScript代码提供桥梁接口libuv事件循环 事件队列 异步IO第三方模块zib http c-ares 1.4.1、libuv Libevent、libev、libuv三个网络库都是c语言实现的异步事件库 libevent :名气最大应用最广泛历史悠久的跨平台事件库 libev :较libevent而言设计更简练性能更好但对Windows支持不够好 libuv :node开发需要一个跨平台的事件库首选了libev但又要支持Windows故重新封装了一套linux下用libev实现Windows下用IOCP实现 1.4.3、c-ares C语言的异步DNS解析库可以很方便的和使用者的事件循环统一起来实现DNS的非阻塞异步解析libcurl, libevent, gevent, nodejs都在使用。 1.5、Nodejs异步IO和事件驱动 IO是应用程序的瓶颈异步IO提升性能无需原地等待返回结果返回操作系统有对应的实现Nodejs单线程配事件驱动架构及libuv实现异步IO 1.5.1、Nodejs异步IO 同步阻塞 所谓同步指的是协同步调。既然叫协同所以至少要有2个以上的事物存在。协同的结果就是 多个事物不能同时进行必须一个一个的来上一个事物结束后下一个事物才开始。 那当一个事物正在进行时其它事物都在干嘛呢 严格来讲这个并没有要求但一般都是处于一种“等待”的状态因为通常后面事物的正常进行都需要依赖前面事物的结果或前面事物正在使用的资源。 因此可以认为同步更希望关注的是从宏观整体来看多个事物是一种逐个逐个的串行化关系绝对不会出现交叉的情况。 所以自然也不太会去关注某个瞬间某个具体事物是处于一个什么状态。 把这个理论应用的出神入化的非“排队”莫属。凡是在资源少需求多的场景下都会用到排队 所谓阻塞指的是阻碍堵塞。它的本意可以理解为由于遇到了障碍而造成的动弹不得。 重复调用IO判断IO是否结束沦陷技术 read select 一个计算机函数位于头文件#include sys/select.h 。该函数用于监视文件描述符的变化情况——读写或是异常。 poll Linux中的字符设备驱动中的一个函数。Linux 2.5.44版本后poll被epoll取代。 和select实现的功能差不多poll的作用是把当前的文件指针挂到等待队列 epoll epoll是Linux内核为处理大批量文件描述符而作了改进的poll是Linux下多路复用IO接口select/poll的增强版本它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率。另一点原因就是获取事件的时候它无须遍历整个被侦听的描述符集只要遍历那些被内核IO事件异步唤醒而加入Ready队列的描述符集合就行了。epoll除了提供select/poll那种IO事件的水平触发Level Triggered外还提供了边缘触发Edge Triggered这就使得用户空间程序有可能缓存IO状态减少epoll_wait/epoll_pwait的调用提高应用程序效率。 kqueue kueue是在UNIX上比较高效的IO复用技术。 所谓的IO复用就是同时等待多个文件描述符就绪以系统调用的形式提供。如果所有文件描述符都没有就绪的话该系统调用阻塞否则调用返回允许用户进行后续的操作。 常见的IO复用技术有select, poll, epoll以及kqueue等等。其中epoll为Linux独占而kqueue则在许多UNIX系统上存在包括OS X好吧现在叫macOS了。。 event ports 跨协作组件的显式调用导致这些组件之间的紧密耦合。 这会降低组件的可维护性、灵活性和可重用性。隐式调用模型解耦了组件从而减少了组件间的依赖关系。 然而隐式调用倾向于忽略组件消息兴趣的历史确定性质导致实现被保护代码污染以强制执行组件的时间顺序协议。 将状态图与隐式调用相结合可以在没有代码污染的情况下直接实现按时间排序的组件协议从而为更清洁、更具适应性的组件协作策略提供了潜力。 异步非阻塞 所谓异步就是步调各异。既然是各异那就是都不相同。所以结果就是 多个事物可以你进行你的、我进行我的谁都不用管谁所有的事物都在同时进行中。 一言以蔽之同步就是多个事物不能同时开工异步就是多个事物可以同时开工。 所谓非阻塞自然是和阻塞相对可以理解为由于没有遇到障碍而继续畅通无阻。 期望无需注定判断的非阻塞IO libuv 是一个跨平台的的基于事件驱动的异步I库原先为 NodeJS 而写。 但是他提供的功能不仅仅是IO包括进程、线程、信号、定时器、进程间通信等。 它围绕着事件驱动的异步I/O模型而设计。 这个库提供不仅仅是对不同I/O轮询机制的简单抽象 还包括 ‘句柄’和‘流’对套接字和其他实体提供了高级别的抽象 也提供了跨平台的文件I/O和线程功能以及其他一些东西。 这是一份图表解释了组成libuv的不同组件和它们相关联的子系统 从上图中我们看到 Libuv使用各平台提供的事件驱动模块实现异步epoll, kqueue, IOCP, event ports。 他用来支持上层非文件io的模块。libuv把上层的事件和回调封装成io观察者uv__io_t放到底层的事件驱动模块。 当事件触发的时候libuv会执行io观察者中的回调。 Libuv实现一个线程池用来支持上层文件io、dns以及用户层耗cpu的任务。Libuv的整体执行架构
1.5.2、Nodejs事件驱动架构
Node.js 事件循环 Node.js 是单进程单线程应用程序但是因为 V8 引擎提供的异步执行回调接口通过这些接口可以处理大量的并发所以性能非常高。 Node.js 几乎每一个 API 都是支持回调函数的。 Node.js 基本上所有的事件机制都是用设计模式中观察者模式实现。 Node.js 单线程类似进入一个while(true)的事件循环直到没有事件观察者退出每个异步事件都生成一个事件观察者如果有事件发生就调用该回调函数. 事件驱动程序 Node.js 使用事件驱动模型当web server接收到请求就把它关闭然后进行处理然后去服务下一个web请求。 当这个请求完成它被放回处理队列当到达队列开头这个结果被返回给用户。 这个模型非常高效可扩展性非常强因为 webserver 一直接受请求而不等待任何读写操作。这也称之为非阻塞式IO或者事件驱动IO 在事件驱动模型中会生成一个主循环来监听事件当检测到事件时触发回调函数。 整个事件驱动的流程有点类似于观察者模式事件相当于一个主题(Subject)而所有注册到这个事件上的处理函数相当于观察者(Observer)。 Node.js 有多个内置的事件我们可以通过引入 events 模块并通过实例化 EventEmitter 类来绑定和监听事件 1.6、Nodejs单线程 Nodejs单线程指的是主线程是单线程单线程实现高并发异步非阻塞IO配合事件回调通知 Nodejs单线程不适合CPU密集型业务场景但是适合IO密集型高并发请求 2、安装Nodejs 官网https://nodejs.org/en/ 中文官网https://nodejs.org/zh-cn/ 中文下载页面https://nodejs.org/zh-cn/download/current/ 2.1、Linux 安装Nodejs
Linux 安装node
官网
mkdir ~/opt
wget https://nodejs.org/dist/v20.17.0/node-v20.17.0-linux-x64.tar.xz
tar -xvf node-v20.17.0-linux-x64.tar.xz -C ~/opt
mv ~/opt/node-v20.17.0-linux-x64 ~/opt/node终端中输入sudo vim ~/.bashrc 在文档最后追加以下内容 export NODE_HOME/home/lhz/opt/node
export PATH$PATH:$NODE_HOME/bin打开新控制台 输入 node -v# 搭建环境时通过如下代码将npm设置成淘宝镜像
npm config set registry http://registry.npmmirror.com --global
# 查看镜像的配置结果
npm config get registry
# 使用nrm工具切换淘宝源
npx nrm use taobao
# 如果之后需要切换回官方源可使用
npx nrm use npm升级npm
npm install -g npmnpm install cnpm -g
npm install yarn -g
npm install pnpm -g2.2、Windows安装Nodejs 控制台输入node --version
node --version控制台输入node
node控制台输入console.log(‘桃李不言下自成蹊’);
console.log(桃李不言下自成蹊);# 搭建环境时通过如下代码将npm设置成淘宝镜像
npm config set registry http://registry.npmmirror.com --global
# 查看镜像的配置结果
npm config get registry
# 使用nrm工具切换淘宝源
npx nrm use taobao升级 npm
npm install -g npmnpm install cnpm -g
npm install yarn -g
npm install pnpm -g3.1、使用WebStorm创建Nodejs项目并运行Nodejs代码
3.2、VSCode运行Nodejs代码
3.2.1、初始化Nodejs项目
# Linux
mkdir code
cd code
sudo npm init --yes# Linux
mkdir code
cd ./project01
npm init --yes返回 Wrote to D:\dev\node\code\project01\package.json: {name: project01,version: 1.0.0,main: index.js,scripts: {test: echo \Error: no test specified\ exit 1},keywords: [],author: ,license: ISC,description:
}编写index.js文件
console.log(我爱你中国亲爱的母亲);控制台执行node index.js
node index.js3.2.2、VScode安装扩展Code Runner
3.3、Node的注意事项(了解) nodejs ECMAScript 核心的api(重点) . 没有 DOM、 BOM 4、Nodejs核心模块API使用
4.1、模块化
4.1.1、模块化历程
传统开发常见问题导致项目难以维护不便于复用 命名冲突和污染代码冗余过多的无效请求文件间依赖关系纷杂 模块化是指将一个大的程序文件拆分为许多小的文件模块然后将小的文件组合起来。 防止命名冲突代码复用高维护性 模块化开发是一种管理方式是一种生产方式一种解决问题的方案一个模块就是实现特定功能的文件有了模块想要什么功能就加载什么模块 模块开发需要遵循一定的规范否则就都乱套了因此才有了后来大家熟悉的AMD规范CMD规范 ES6之前本身没有模块化社区衍生出模块化产品 CommonJS NodeJS、BrowserifyAMD RequireJSCMD SeazJS CommonJS规范 CommonJS 是以在浏览器环境之外构建 javaScript 生态系统为目标而产生的写一套规范 主要是为了解决 javaScript 的作用域问题而定义的模块形式可以使每个模块它自身的命名空间中执行该规范的主要内容是 模块必须通过 module.exports 导出对外的变量或者接口 通过 require() 来导入其他模块的输出到当前模块的作用域中 目前在服务器和桌面环境中node.js 遵循的是 CommonJS 的规范 CommonJS 对模块的加载时同步的 模块引用模块标识模块定义 module属性 任意js文件就是一个模块可以直接使用module属性id返回模块标识符一般是一个据对路径filename返回文件模块决定路径loaded返回布尔值表示模块是否加载完成parent返回对象存放调用当前模块的模块children返回数组存放当前模块调用其他模块exports返回当前模块需要暴露的内容paths返回数组存放不同目录下的node_module位置 require属性 基本功能读入并且执行一个模块文件reslove模块文件据对路径extensions依据不同后缀名执行解析操作main返回主模块对象 AMD AMD 即Asynchronous Module Definition中文名是“异步模块定义”的意思它采用异步方式加载模块模块的加载不影响它后面语句的运行所有依赖这个模块的语句都定义在一个回调函数中等到加载完成之后这个回调函数才会运行 一般来说AMD是 RequireJS 在推广过程中对模块定义的规范化的产出因为平时在开发中比较常用的是require.js进行模块的定义和加载 一般是使用define来定义模块使用require来加载模块 AMD 主要是为前端 js 的表现指定的一套规范而 CommonJS 是主要为了 js 在后端的表现制定的它不适合前端 AMD 也是采用 require() 语句加载模块的但是不同于 CommonJS 它有两个参数require([‘模块的名字’]callBack)requireJs 遵循的就是 AMD 规范 // 定义模块
define(math,[jquery], function ($) {//引入jQuery模块return {add: function(x,y){return x y;}};
});
// 调用模块
require([jquery,math], function ($,math) {console.log(math.add(10,100));//110
});CMD CMD 即Common Module Definition通用模块定义CMD规范是国内发展出来的同时CMD是在SeaaJS推广的过程中形成的 CMD和AMD要解决的都是同个问题在使用上也都很像只不过两者在模块定义方式和模块加载时机上有所不同 CMD 也是通过异步的方式进行模块的加载的不同于 AMD 的是CMD 的加载是按照就近规则进行的 AMD 依赖的是前置CMD 在加载的使用的时候会把模块变为字符串解析一遍才知道依赖了哪个模块 // 定义模块 myModule.js
define(function(require, exports, module) {var $ require(jquery.js)$(div).addClass(active);exports.data 1;
});// 加载模块
seajs.use([myModule.js], function(my){var star my.data;console.log(star); //1
});ES6中的模块化 在ES6没有出来之前社区制定了一些模块加载方案最主要的有 CommonJS 和 AMD 两种前者用于服务器后者用于浏览器 ES module 在语言标准的层面上实现了模块功能而且相当简单完全可以取代 CommonJS 和 AMD 规范成为浏览器和服务器通用的模块解决方案 ES module 中的模块化有一个比较大的特点就是实现尽量的静态化 4.1.2、前端模块化
m01.js
export const slogan 桃李不言下自成蹊;
export const love function () {console.log(我爱你中国亲爱的母亲);
}m01.html
!DOCTYPE html
html langenheadmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0title模块化/title
/headbody/body/html
script typemoduleimport * as m01 from ./src/js/m01.jsconsole.log(m01.slogan);m01.love()
/scriptm02.js
const slogan 桃李不言下自成蹊;
const love function () {console.log(我爱你中国亲爱的母亲);
}
export{slogan,love}m02.html
!DOCTYPE html
html langenheadmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0title模块化/title
/headbody/body/html
script typemoduleimport * as m02 from ./src/js/m02.jsconsole.log(m02.slogan);m02.love()// 解构赋值import {slogan,love} from ./src/js/m02.js;console.log(slogan);love()
/scriptm03.js
export default{slogan : 桃李不言下自成蹊,love :function () {console.log(我爱你中国亲爱的母亲);}
}m03.html
!DOCTYPE html
html langenheadmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0title模块化/title
/headbody/body/html
script typemoduleimport * as m03 from ./src/js/m03.jsconsole.log(m03.default.slogan);m03.default.love()// 解构赋值import {default as m003} from ./src/js/m03.js;console.log(m003.slogan);m003.love()// 针对默认暴露 简便形式import m30 from ./src/js/m03.js;console.log(m30.slogan);m30.love()
/scriptapp.js
import * as m001 from ./m01.js
import * as m002 from ./m02.js
import {default as m300} from ./m03.js
window.console.log(m001.slogan);
m001.love();
window.console.log(m002.slogan);
m002.love();
window.console.log(m300.slogan);
m300.love();app.html
!DOCTYPE html
html langenheadmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0title模块化/title
/headbody/body/html
script src./src/js/app.js typemodule charsetutf-8/script由于兼容性问题需要将高版本js代码转化为兼容性较好的低版本代码 使用babel可以轻松的进行转换 安装三个工具babel-cli babel-preset-env browserify(webpack) 首先使用 init 初始化 npm 包文件
npm init --yes 安装babel工具
npm i babel-cli babel-preset-env browserify -D 编译(js为源文件夹 dist/js 为目标文件夹会自动生成) –presetsbabel-preset-env /可以单独配置babel配置文件实现 npx babel src/js -d dist/js --presetsbabel-preset-env browserify app.js中 require 浏览器还是不识别需要再次转换 npx browserify dist/js/app.js -o dist/bundle.js npm init --yes
npm i babel-cli babel-preset-env browserify -D
npx babel src/js -d dist/js --presetsbabel-preset-env
npx browserify dist/js/app.js -o dist/bundle.js bundle.html
!DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titlebundle/title
/head
body/body
/html
script srcdist/bundle.js typetext/javascript charsetutf-8/script引入npm模块
npm i jqueryjquery.js
// const $ require(jquery)
import $ from jquery
$(body).css(background, #FA6060);npx babel src/js -d dist/js --presetsbabel-preset-env
npx browserify dist/js/jquery.js -o dist/jquery.js !DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titlejquery/title
/head
body/body
/html
script src./dist/jquery.js/script4.1.3、Nodejs模块化
m01.js
const slogan 桃李不言下自成蹊;
const love () {return 我爱你中国亲爱的母亲;
}
module.exports {slogan: slogan,love: love
}r01.js
const m01 require(./src/js/m01);
console.log(m01.slogan);
console.log(m01.love());m02.js
console.log(module);r02.js
const m02 require(./src/js/m02);m03.js
exports.name lhzr03.js
const m03 require(./src/js/m03);
console.log(m03);m04.js
console.log(我嫁人了);r04.js
const m04 require(./src/js/m04);
console.log(我娶你);m05
console.log(我嫁人了);
let date new Date();
while (new Date() - date 6000) {}r05.js
const m05 require(./src/js/m05);
console.log(我娶你);4.2、Nodejs全局对象 与浏览器中的window不完全相同Nodejs全局对象global 4.3、Nodejs全局变量 __filename返回正在执行脚本文件的绝对路径__dirame返回正在执行脚本文件所在目录的相对路径time类函数执行顺序与事件循环间的关系process提供与当前进程互动的接口require加载模块exports模块导出module模块导出this module.exports 初始值为一个空对象 {}exports 是指向的 module.exports 的引用require() 返回的是 module.exports 而不是 exports4.3.1、process
// const fs require(fs);console.log(process.memoryUsage());
console.log(process.cpuUsage());
console.log(process.cwd());
console.log(process.version);
console.log(process.versions);
console.log(process.arch);
console.log(process.env.Path);
console.log(process.env.USERPROFILE);
console.log(process.platform);console.log(process.argv);
console.log(process.pid);
// 当前程序运行时间
console.log(process.uptime());// 事件
process.on(exit,function (code) {console.log(exit : code)
});process.on(beforeExit,function (code) {console.log(beforeExit : code)
});//{
// rss: 18563072,
// heapTotal: 4321280,
// heapUsed: 3440000,
// external: 212402,
// arrayBuffers: 11146
// }
// rss: (Resident Set Size)操作系统分配给进程的总的内存大小。
// heapTotal堆的总大小包括3个部分
// 已分配的内存用于对象的创建和存储对应于heapUsed
// 未分配的但可用于分配的内存
// 未分配的但不能分配的内存例如在垃圾收集GC之前对象之间的内存碎片
// heapUsed: 已分配的内存即堆中所有对象的总大小是heapTotal的子集。
// external: 进程使用到的系统链接库所占用的内存
// arrayBuffers:4.3.2、path basename()获取路径中的基础名称dirname()获取路径中的目录名extname()获取后缀名isAbsolute()获取路径是否为绝对路径join()路径拼接reslove()返回绝对路径parse()解析路径formart()序列化路径normalize()规范化路径 5、Nodejs创建HTTP服务
5.1、Nodejs创建HTTP服务
mkdir httpServer
cd httpServer
npm init --yes新建文件node.js,编写代码如下:
// 引入http模块
var http require(http);// 使用http模块创建httpServer
var server http.createServer();// 处理HTTP请求
server.on(request, function (request, response) {// 设置响应头response.writeHead(200, { Content-type: text/html;charsetutf-8 });// 给客户端发送字符串response.write(h3我爱你中国h3);// 结束响应 (关闭输出流)response.end();
});// 端口监听 启动的服务
server.listen(6633, function () {console.log(服务已启动请访问http://127.0.0.1:6633);
});node app.js5.2、nodemon
全局安装nodemon
npm i nodemon -g在项目目录以开发模式安装nodemon
npm i nodemon -D编写package.json文件在scripts中增加以下内容:
start: nodemon app.js修改后的package.json文件内容如下:
{name: httpserver,version: 1.0.0,description: ,main: index.js,scripts: {start: nodemon app.js,test: echo \Error: no test specified\ exit 1},keywords: [],author: ,license: ISC,devDependencies: {nodemon: ^2.0.12}
}vue
使用vite创建vue工程
npm create vitelatest -- --template vue-appcd vue-app
npm install
npm run dev1、chap01 文本插值 script setup langts
import {ref} from vue;
// ref 使用该函数装饰响应式的值
const slogan ref(以吾辈之青春捍卫盛世之华夏);
const msg ref(欢迎台湾同胞回家);
const html ref(a hrefhttps://space.bilibili.com/480308139/李昊哲小课/a);
const count ref(0);
/scripttemplate!--组件index.html - main.ts - chap01/HelloLhz.vue - chap01/LhzA.vue--h1文本插值/h1div{{slogan}}/divdiv v-textmsg/div!-- v-text innerText --div v-texthtml/div!-- v-html innerHTML --div v-htmlhtml/divdiv v-textcount/div
/templatestyle scoped/style事件处理 script setup langts
import {ref} from vue;
// ref 使用该函数装饰响应式的值
const slogan ref(以吾辈之青春捍卫盛世之华夏);
const msg ref(欢迎台湾同胞回家);
const html ref(a hrefhttps://space.bilibili.com/480308139/李昊哲小课/a);
const count ref(0);
const getMsg () {window.alert(msg.value);
}
const fun01 () {window.alert(1);
}
const fun02 () {window.alert(2);
}
const fun03 (e) {console.log(e);
}
const accumulation () {count.value;
}
/scripttemplateh1事件处理/h1div v-textmsg/div!-- 默认情况下调用无参函数不加括号 --button typebutton v-on:clickgetMsg你过来呀/button!-- 默认情况下调用无参函数也可以加括号 --button typebutton v-on:clickgetMsg()你过来呀()/button!-- 动作指令 语法糖 --button typebutton clickgetMsg语法糖/button!-- 同一个动作指令调同时调用多个函数的时候 函数需要加括号 --button typebutton clickfun01(),fun02()多事件绑定/buttonbutton typebutton clickfun03($event)事件对象参数/buttonbutton typebutton clickcount v-textcount/buttonbutton typebutton clickaccumulation v-textcount/button!-- v-once 表示其内容只会被渲染一次 --divspan v-textcount v-once/span/div
/templatestyle scoped/style事件修饰符 script setup langts
const out () {window.alert(out_box);
}
const inner () {window.alert(inner_box);
}
const go () {window.alert(once);
}/scripttemplate
divh1事件修饰符/h1!--prevent 取消事件默认行为stop 阻止事件冒泡once 只执行一次 仅一次生效--divform actionhttps://www.baidu.com/s? methodgetinput typesearch namewd idinput typesubmit value千度以下你就知道 click.prevent/form/divdiv idout_box clickoutdiv idinner_box click.stopinner!-- 链式调用 方法进执行一次 但 prevent 仅一次生效 --a hrefhttps://space.bilibili.com/480308139/ click.prevent.oncego李昊哲-小课/abr!-- 分开写 一切正常 --a hrefhttps://space.bilibili.com/480308139/ click.prevent click.oncego李昊哲/a/div/div
/div
/templatestyle scoped
#out_box{margin-top: 30px;width: 450px;height: 450px;background-color: #4365c3;text-align: center;position: relative;//color: #ffffff;
}
#inner_box{width: 300px;height: 300px;background-color: #929854;position: absolute;left: 75px;top: 75px;
}
/style属性绑定 script setup langts
// 引入图片静态资源
import logo from ../../assets/logo.png;
import {ref} from vue;const alt ref(vue logo)
const title ref(忘记历史等于背叛);
const width ref(600);
const id ref(img-attr);
/scripttemplate
h1属性绑定/h1img :srclogo :altalt :titletitle :widthwidth :idid/
/templatestyle scoped/style动态属性 script setup langts
// 引入图片静态资源
import logo from ../../assets/logo.png;
import coding from ../../assets/coding.jpg;
import {ref} from vue;const alt ref(vue logo)
const title ref(忘记历史等于背叛);
const figure ref(600);
const id ref(img-attr);
const woh ref(width);
const changeAttr () {woh.value woh.value width ? height : width;
}
/scripttemplateh1动态属性/h1img :altalt :srccoding :titletitle :[woh]figure :idid clickchangeAttr
/templatestyle scoped/style2、chap02 v-show script setup langts
import computer_room from ../../assets/computer_room.png;
import {ref} from vue;const alt ref(computer_room);
const figure ref(600);
const title ref(忘记历史等于背叛);
const condition ref(true)
/scripttemplateh1 clickcondition !conditionv-show/h1!-- v-show 控制元素是否显示 相当于 在css样式中使用 display; --!-- v-show 值为 true 相当于 在css样式中使用 display: block; --!-- v-show 值为 false 相当于 在css样式中使用 display: none; --img :srccomputer_room :altalt :widthfigure :titletitle v-showcondition/
/templatestyle scoped/stylev-if script setup langts
import computer_room from ../../assets/computer_room.png;
import {ref} from vue;const alt ref(computer_room);
const figure ref(600);
const title ref(忘记历史等于背叛);
const condition ref(true)
const gender ref(男)
const changeGender () {condition.value !condition.valuegender.value condition.value ? 男 : 女
}
const weekDay ref(3);
/scripttemplateh1 clickcondition !conditionv-if/h1!-- v-if 控制元素是否显示 相当于 dom是否存在 --img :srccomputer_room :altalt :widthfigure :titletitle v-ifcondition/h1 clickchangeGender v-textgender/h1h1 v-ifcondition男性/h1h1 v-else女性/h1span v-ifweekDay % 7 1星期一/spanspan v-else-ifweekDay % 7 2星期二/spanspan v-else-ifweekDay % 7 3星期三/spanspan v-else-ifweekDay % 7 4星期四/spanspan v-else-ifweekDay % 7 5星期五/spanspan v-else-ifweekDay % 7 6星期六/spanspan v-else星期日/span
/templatestyle scoped/stylev-for script setup langts
import {reactive} from vue;const names reactive([李昊哲, 大美丽, 李胜龙, 小可爱]);
const person reactive({name: 李昊哲,age: 43,gender: true
})const persons reactive([{id: 1,name: 李昊哲,age: 35,gender: true,}, {id: 2,name: 大美丽,age: 39,gender: false,}, {id: 3,name: 李胜龙,age: 39,gender: true,}, {id: 4,name: 小可爱,age: 27,gender: false,}
]);
/scripttemplateh1v-for/h1ul!-- 第一个参数是列表元素 第二个参数是列表索引 --li v-for(name,index) in names v-textname :keyname/li/ulul!-- 第一个参数是列表元素 第二个参数是列表索引 --li v-for(name,index) in names v-textnames[index] :keyname index/li/ul!-- 第一个参数是对象属性值 第二个参数是对象属性名 --div v-for(value,field) in person v-textfield : value :keyfield : value/divtabletheadtrthid/thth姓名/thth年龄/thth性别/th/tr/theadtbodytr v-for(person,index) in persons :keyfieldtd v-for(value,filed) in person v-textvalue/td/tr/tbody/tabletabletheadtrthid/thth姓名/thth年龄/thth性别/th/tr/theadtbodytr v-for(person,index) in persons :keyfieldtd v-textperson.id/tdtd v-textperson.name/tdtd v-textperson.age/tdtd v-textperson.gender true? 男: 女/td/tr/tbody/table
/templatestyle scoped
ul li {list-style: none;
}table td {text-align: center;padding: 10px 30px;
}
/style计算属性 script setup langts
import {computed, reactive, ref} from vue;const slogan ref(友谊第一比赛第二);
const time ref(0);
const countdown setInterval(() {time.value;if (time.value 10) {disabled.value true;clearInterval(countdown);}
}, 1000);const team reactive({china: 0,korea: 0
});
const result ref(computed(() {if (team.china team.korea) {return 中国队领先} else if (team.china team.korea) {return 韩国队领先} else {return 势均力敌;}
}))
const disabled ref(false);
/scripttemplateh1计算属性/h1h1 v-textslogan/h1h2比赛时间span v-texttime/span/h2h2直播播报span v-textresult/span/h2h2中国队进球数span v-textteam.china/spanbutton typebutton clickteam.china :disableddisabled点击中国队进一球/button/h2h2韩国队进球数span v-textteam.korea/spanbutton typebutton clickteam.korea :disableddisabled点击韩国队进一球/button/h2
/templatestyle scoped/style侦听器 script setup langts
import {ref, watch, watchEffect} from vue;const msg ref(铭记历史勿忘国耻);
watchEffect(() {console.log(watchEffect msg msg.value)
});// 第一个参数为侦听的对象
watch(msg, (value, oldValue, onCleanup) {// 第一个参数是变化后的值// 第二个参数是变化前的值console.log(value ${value} \t oldValue ${oldValue});
}, {immediate: true,// deep:当需要对对象等引用类型数据进行深度监听时设置deep: true,默认值是false。// immediate默认情况下watch是惰性的设置immediate: true时watch会在初始化时立即执行回调函数一次。// flush控制回调函数的执行时机。它可设置为 pre、post 或 sync。// pre默认值当监听的值发生变更时优先执行回调函数在dom更新之前执行。// postdom更新渲染完毕后执行回调函数。// sync:一旦监听的值发生了变化同步执行回调函数建议少用
});
/scripttemplateinput typetext name id v-modelmsgh1 v-textmsg/h1
/templatestyle scoped/style侦听器案例 script setup langts
import {computed, reactive, ref, watch} from vue;const slogan ref(友谊第一比赛第二);
const time ref(0);
const countdown setInterval(() {time.value;if (time.value 10) {disabled.value true;clearInterval(countdown);}
}, 1000);const team reactive({china: 0,korea: 0
});
const result ref(势均力敌)
watch(team, (value, oldValue, onCleanup) {if (team.china team.korea) {result.value 中国队领先} else if (team.china team.korea) {result.value 韩国队领先} else {result.value 势均力敌;}
}, {deep: true})
const disabled ref(false);
/scripttemplateh1计算属性/h1h1 v-textslogan/h1h2比赛时间span v-texttime/span/h2h2直播播报span v-textresult/span/h2h2中国队进球数span v-textteam.china/spanbutton typebutton clickteam.china :disableddisabled点击中国队进一球/button/h2h2韩国队进球数span v-textteam.korea/spanbutton typebutton clickteam.korea :disableddisabled点击韩国队进一球/button/h2
/templatestyle scoped/style3、chap03 表单操作 v-model script setup langts
import {ref} from vue;const msg ref(山河统一解放台湾);
const male ref(1);
const female ref(0);
const checked ref(true);
const hobbies ref([swimming, skiing]);
const hometown ref(jilin);
const fruits ref([pear]);
/scripttemplateh1v-model/h1input typetext name id v-modelmsg /h1 v-textmsg/h1性别label formale男input typeradio namegender idmale v-modelmale //labelnbsp;nbsp;nbsp;nbsp;label forfemale女input typeradio namegender idfemale v-modelfemale :checkedchecked //labelbrlabel forremember记住我input typecheckbox nameremember idremember :checkedchecked //labelh3多选按钮/h3爱好nbsp;nbsp;nbsp;nbsp;input typecheckbox idswimming namehobby valueswimming v-modelhobbiesnbsp;nbsp;nbsp;nbsp;label forrunning跑步/labelinput typecheckbox idrunning namehobby valuerunning v-modelhobbiesnbsp;nbsp;nbsp;nbsp;label forskiing滑雪/labelinput typecheckbox idskiing namehobby valueskiing v-modelhobbiesbrh3单选下拉列表/h3籍贯nbsp;nbsp;nbsp;nbsp;select namehometown idhometown v-modelhometownoption valuebeijing北京/optionoption valueshanghai上海/optionoption valuejilin吉林/option/selecth3多选下拉列表/h3水果nbsp;nbsp;nbsp;nbsp;select namefruits idfruits multiple v-modelfruitsoption valuebanana香蕉/optionoption valueapple苹果/optionoption valuepear梨/option/select
/templatestyle scoped/style4、chap04 父子组件 script setup langts
const props defineProps([person,msg])
const {msg} props
const {person} props
/scripttemplate!-- 父子组件 defineProps 传值 子组件 --h1 v-textprops.msg/h1h1 v-textprops.person.realName/h1h1 v-textprops.person.slogan/h1h1 v-textmsg/h1h1 v-textperson.realName/h1h1 v-textperson.slogan/h1
/templatestyle scoped/styledefineProps script setup langts
const props defineProps([person,msg])
const {msg} props
const {person} props
/scripttemplate!-- 父子组件 defineProps 传值 子组件 --h1 v-textprops.msg/h1h1 v-textprops.person.realName/h1h1 v-textprops.person.slogan/h1h1 v-textmsg/h1h1 v-textperson.realName/h1h1 v-textperson.slogan/h1
/templatestyle scoped/styleuseAttrs script setup langts
import {useAttrs} from vue;defineOptions({inheritAttrs: false,
})const attrs useAttrs()
const {msg} attrs
const {person} attrs
/scripttemplate!-- 父子组件 useAttrs 传值 子组件 --h1 v-textattrs.msg/h1h1 v-textattrs.person.realName/h1h1 v-textattrs.person.slogan/h1h1 v-textmsg/h1h1 v-textperson.realName/h1h1 v-textperson.slogan/h1
/templatestyle scoped/styledefineEmits script setup langts
import LhzE from ./LhzE.vue;
import {reactive, ref} from vue;const msg ref(忘记历史等于背叛);
const person reactive({realName: 李昊哲,slogan: 河山统一解放台湾
});
const updateName (value) {person.realName value;
}
/scripttemplateh1父组件span v-textmsg/span/h1h1父组件span v-textperson.realName/span/h1h1父组件span v-textperson.slogan/span/h1hr!-- 父子组件 defineProps 传值 父组件 --lhz-e :personperson :msgmsg updateupdateName/
/templatestyle scoped/stylescript setup langts
import {ref} from vue;const props defineProps([person, msg])
const {msg} props
const {person} props
const newName ref();
const emit defineEmits()
const updateName () {// 第一个参数为 父组件接收子组件的动作指令// 第二个参数为 子组件向父组件发送的数据emit(update, newName)
}
/scripttemplateS!-- 父子组件 defineProps 传值 子组件 --input typetext name id autocompleteoff v-modelnewName inputupdateName!-- 父子组件 defineProps 传值 子组件 --h1子组件span v-textmsg/span/h1h1子组件span v-textperson.realName/span/h1h1子组件span v-textperson.slogan/span/h1
/templatestyle scoped/styleprovide 与 inject const slogan Symbol();
const obj Symbol();
const msg Symbol();
const location Symbol();
export {slogan,obj,msg,location
}script setup langts
import LhzM from ./LhzM.vue;
import {provide, reactive, ref} from vue;
import {slogan, obj, msg, location} from ./keysconst my_slogan ref(河山一统);
const my_obj reactive({slogan: 解放台湾
});const my_msg () {return my_slogan;
}
// provide(slogan, my_slogan);
// provide(obj, my_obj);
// provide(msg, my_msg);provide(slogan, my_slogan);
provide(obj, my_obj);
provide(msg, my_msg);
provide(location, {my_slogan, my_obj, my_msg});
/scripttemplateh1LhzL/h1lhz-m/
/templatestyle scoped/stylescript setup langts
import LhzN from ./LhzN.vue;
/scripttemplateh1LhzM/h1lhz-n/
/templatestyle scoped/stylescript setup langts
import {inject, ref} from vue;
import {slogan, obj, msg,location} from ./keys
// const new_slogan inject(slogan)
// const new_obj inject(obj)
// const new_msg01 inject(msg)()
// const new_msg02 inject(msg)
// const content ref(new_msg02())const new_slogan inject(slogan)
const new_obj inject(obj)
const new_msg01 inject(msg)()
const new_msg02 inject(msg)
const content ref(new_msg02())
const {my_slogan,my_obj,my_msg} inject(location)
const result ref(my_msg())
/scripttemplateh1LhzN/h1div v-textnew_slogan/divdiv v-textnew_obj/divdiv v-textnew_obj.slogan/divdiv v-textnew_msg01/divdiv v-textcontent/divhrdiv v-textmy_slogan/divdiv v-textmy_obj/divdiv v-textmy_obj.slogan/divdiv v-textresult/div
/templatestyle scoped/style选项卡案例 script setup langts
import LhzTabBtn from ./LhzTabBtn.vue;
import LhzTabContent from ./LhzTabContent.vue;
import {ref} from vue;const index ref(0);
const changeTab (param) {index.value param;
}
/scripttemplatelhz-tab-btn changeTabchangeTab/lhz-tab-content :tabIndexindex/
/templatestyle scoped
/stylescript setup langts
import {reactive} from vue;const lis reactive([{title: 商品介绍,classList: [current],}, {title: 规格包装,classList: [],}, {title: 售后保障,classList: [],}, {title: 商品评价(66),classList: [],}, {title: 手机社区,classList: [],}
]);
const emit defineEmits([changeTab]);
const change (index) {// 遍历列表中中的所有元素outer:for (const item of lis) {// 获取列表中当前元素的的 classList 属性let class_list item.classList;// 遍历 classList 即当前元素的css样式列表for (let i 0; i class_list.length; i) {// 获取当前元素的css样式列表if (class_list[i] current) {// 如果当前的 css 样式 列表中 存在 current 样式 则将 current 从当前列表移除class_list.splice(i, 1);// 结束外出循环break outer;}}}// 被点击的元素添加 current 样式lis[index].classList.push(current);// 将被点击的元素的 index 值 向上发射emit(changeTab, index);
}
/scripttemplate!-- 选项卡按钮 --div classtab-btnulli v-for(item,index) in lis :keyitem.title index v-textitem.title :classitem.classList clickchange(index)/li/ul/div
/templatestyle scoped
.tab-btn {width: 990px;border-bottom: 1px solid #e4393c;color: #666;cursor: pointer;position: absolute;left: 0;top: 0;
}ul li {list-style: none;float: left;font-size: 14px;width: 160px;height: 38px;line-height: 38px;text-align: center;
}.current {background-color: #e4393c;color: #fff;
}
/stylescript setup langts
import {reactive, useAttrs, watchEffect} from vue;const contents reactive([{title: 商品介绍,isShow: true}, {title: 规格包装,isShow: false}, {title: 售后保障,isShow: false}, {title: 商品评价(66),isShow: false}, {title: 手机社区,isShow: false}
]);const attrs useAttrs();
watchEffect(() {for (const index in contents) {contents[index].isShow attrs.tabIndex parseInt(index)}
})
/scripttemplatediv classtab-contentdiv v-for(content,index) in contents :keycontent.title index v-textcontent.title v-showcontent.isShow/div/div
/templatestyle scoped
.tab-content {width: 100%;color: #666;background-color: #ffffff;position: absolute;top: 80px;left: 0;padding: 30px;font-size: 66px;
}
/style5、chap05 插槽 slot script setup langts
import LhzA from ./LhzA.vue;
import {ref} from vue;
const username ref(李胜龙);
const love () {username.value 李昊哲;
}
/scripttemplatelhz-atemplate v-slot:nav!-- 具名插槽 --div头部导航/div/templatetemplate v-slot:default!-- 默认插槽 --input typetext autocompleteoff v-modelusernamebutton typebutton clicklovelove/button/templatetemplate #footer!-- 具名插槽缩写 --div友情链接/div/templatetemplate #lhz-aa/template #lhz-bb{names}ulli v-for(name,index) in names v-textname/li/ul/templatetemplate #lhz-cc{item}span v-textitem/span/template/lhz-a
/templatestyle scoped/stylescript setup langts
import {reactive} from vue;const names reactive([李昊哲, 李大宝, 李胜龙]);
/scripttemplateslot namenav/slot/h1我是LhzA/h1slot/slot namefooter/hrulli v-for(name,index) in names v-textname/li/ulhrslot namelhz-aaulli v-for(name,index) in names v-textname/li/ul/slotslot namelhz-bb :namesnames/ulli v-for(item,index) in namesslot namelhz-cc :itemitem//li/ul
/templatestyle scoped/style6、chap06
步骤 安装路由 npm install vue-router4准备视图组件 HomeView.vueAboutView.vue 编写路由规则 import {createMemoryHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;const routes [{path: /home, component: HomeView},{path: /about, component: AboutView},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default router在 main.ts 或者 main.js 文件中引入了并使用路由规则 import { createApp } from vue
import ./style.css
import router from ./router/chap06/router.ts;
import App from ./App.vue
const app createApp(App)
app.use(router)
app.mount(#app) 在组件中编写路由跳转按钮 script setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linkrouter-view/
/templatestyle scoped/style路由模式 hash模式 memory模式 html5模式 router.ts 路由配置文件 import {createMemoryHistory, createWebHistory,createWebHashHistory,createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;const routes [{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default router处理404 准备404页面 script setup langts/scripttemplateh1NotFound/h1
/templatestyle scoped/stylerouter.ts 路由配置文件 import {createMemoryHistory, createWebHistory,createWebHashHistory,createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;const routes [// 处理404{path:/:pathMatch(.*)*,component:NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default router动态路由传参
script setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory,createWebHashHistory,createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;const routes [// 处理404{path:/:pathMatch(.*)*,component:NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {computed, reactive, ref} from vue;
import {useRoute} from vue-router;const orders reactive([{id: 1,productName: 商品1},{id: 2,productName: 商品2},{id: 3,productName: 商品3},{id: 4,productName: 商品4},{id: 5,productName: 商品5},
]);
const productName ref(computed(() {const order orders.find(item item.id useRoute().params.id);if (order) {return order.productName;} else {return null;}
}));
/scripttemplateh1Order/h1h1 v-textproductName/h1
/templatestyle scoped/style嵌套路由
script setup langts/scripttemplateh1UserLoginView/h1
/templatestyle scoped/stylescript setup langts/scripttemplateh1UserDetailView/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLink
/templatestyle scoped/style命名路由与别名
script setup langts/scripttemplateh1TestA/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;
import TestA from ../../views/chap06/TestA.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},{path: /testA,// 命名理由name: nameA,// 路由别名 指的是路径的别名alias: [/ta1, /ta2],component: TestA},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{name:nameA}Go to nameA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLink
/templatestyle scoped/style路由传参
params
script setup
import {computed, ref} from vue;
import {useRoute} from vue-router;const id ref(computed(() {return useRoute().params.id;
}));
/scripttemplateh1TestB/h1h1 v-textid/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;
import TestA from ../../views/chap06/TestA.vue;
import TestB from ../../views/chap06/TestB.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},{path: /testA,// 命名理由name: nameA,// 路由别名 指的是路径的别名alias: [/ta1, /ta2],component: TestA},{// 路由传参name: nameB,path: /testB/:id,component: TestB},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLinkbr/!-- 路由传参 --router-link :to{ name: nameB, params: { id: 3 }}Go to nameB/router-link
/templatestyle scoped/stylequery
script setup
import {computed, ref} from vue;
import {useRoute} from vue-router;const id ref(computed(() {return useRoute().params.id;
}));
/scripttemplateh1TestB/h1h1 v-textid/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;
import TestA from ../../views/chap06/TestA.vue;
import TestB from ../../views/chap06/TestB.vue;
import TestC from ../../views/chap06/TestC.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},{path: /testA,// 命名理由name: nameA,// 路由别名 指的是路径的别名alias: [/ta1, /ta2],component: TestA},{// 路由传参name: nameB,path: /testB/:id,component: TestB},{// 路由传参name: nameC,path: /testC,component: TestC},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLinkbr/!-- 路由传参 --router-link :to{ name: nameB, params: { id: 3 }}Go to nameB/router-linkrouter-link :to{ name: nameC, query: { id: 3 }}Go to nameC/router-link
/templatestyle scoped/style重定向
import {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;
import TestA from ../../views/chap06/TestA.vue;
import TestB from ../../views/chap06/TestB.vue;
import TestC from ../../views/chap06/TestC.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},{path: /testA,// 命名理由name: nameA,// 路由别名 指的是路径的别名alias: [/ta1, /ta2],component: TestA},{// 路由传参name: nameB,path: /testB/:id,component: TestB},{// 路由传参name: nameC,path: /testC,component: TestC},{path: /test_redirect,// redirect: /testA,// redirect: /ta1,redirect: {name: nameA},},{name: redirect_with_query,path: /redirect_with_query,redirect: {name: nameC},},{name: redirect_with_params,path: /redirect_with_params/:id,redirect: to {console.log(to)// 方法接收目标路由作为参数// return 重定向的字符串路径/路径对象// return {path: /testC, query: {id: to.params.id}}return {name: nameB, params: {id: to.params.id}}},},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLinkbr/!-- 路由传参 --router-link :to{ name: nameB, params: { id: 3 }}Go to nameB/router-linkrouter-link :to{ name: nameC, query: { id: 3 }}Go to nameC/router-linknbsp;nbsp;nbsp;nbsp;!-- redirect 重定向 --RouterLink :to{path: /test_redirect}Go to test_redirect/RouterLinknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_query, query: { id: 3 }}Go to redirect_with_query/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_params, params: { id: 3 }}Go to redirect_with_params/router-link
/templatestyle scoped/styleprops传递路由组件
script setup langts
import {ref} from vue;const props defineProps([id])
const id ref(props.id)
/scripttemplateh1TestD/h1h1将 props 传递给路由组件 布尔模式/h1h1 v-textid/h1
/templatestyle scoped/stylescript setup langts
import {ref} from vue;const props defineProps([did])
const id ref(props.did)
/scripttemplateh1TestE/h1h1将 props 传递给路由组件 对象模式/h1h1 v-textdid/h1
/templatestyle scoped/stylescript setup langts
import {ref} from vue;const props defineProps([did])
const id ref(props.did)
/scripttemplateh1TestF/h1h1将 props 传递给路由组件 对象模式/h1h1 v-textdid/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-routerimport HomeView from ../../views/chap06/HomeView.vue;
import AboutView from ../../views/chap06/AboutView.vue;
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import OrderView from ../../views/chap06/OrderView.vue;
import UserLoginView from ../../views/chap06/UserLoginView.vue;
import UserDetailView from ../../views/chap06/UserDetailView.vue;
import TestA from ../../views/chap06/TestA.vue;
import TestB from ../../views/chap06/TestB.vue;
import TestC from ../../views/chap06/TestC.vue;
import TestD from ../../views/chap06/TestD.vue;
import TestE from ../../views/chap06/TestE.vue;
import TestF from ../../views/chap06/TestF.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{path: /, component: HomeView},{path: /home, component: HomeView},{path: /about, component: AboutView},// {path: /order/:id, component: OrderView},{path: /order/:id(\\d), component: OrderView},// {path: /order/:id(.*), component: OrderView},// {path: /order/:id(.?), component: OrderView},{// 嵌套路由path: /user,children: [{path: login, component: UserLoginView},{path: detail, component: UserDetailView},]},{path: /testA,// 命名理由name: nameA,// 路由别名 指的是路径的别名alias: [/ta1, /ta2],component: TestA},{// 路由传参name: nameB,path: /testB/:id,component: TestB},{// 路由传参name: nameC,path: /testC,component: TestC},{path: /test_redirect,// redirect: /testA,// redirect: /ta1,redirect: {name: nameA},},{name: redirect_with_query,path: /redirect_with_query,redirect: {name: nameC},},{name: redirect_with_params,path: /redirect_with_params/:id,redirect: to {console.log(to)// 方法接收目标路由作为参数// return 重定向的字符串路径/路径对象// return {path: /testC, query: {id: to.params.id}}return {name: nameB, params: {id: to.params.id}}},},// 将 props 传递给路由组件{name: nameD,path: /testD/:id,component: TestD,// 布尔模式props: true,},{name: nameE,path: /testE/:id,component: TestE,// 对象模式props: to ({did: to.params.id}),},{name: nameF,path: /testF,component: TestF,// 对象模式props: to ({did: to.query.id}),},
]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routerscript setup langts
import {useRoute} from vue-router;const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkrouter-view/nbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLinkbr/!-- 路由传参 --router-link :to{ name: nameB, params: { id: 3 }}Go to nameB/router-linkrouter-link :to{ name: nameC, query: { id: 3 }}Go to nameC/router-linknbsp;nbsp;nbsp;nbsp;!-- redirect 重定向 --RouterLink :to{path: /test_redirect}Go to test_redirect/RouterLinknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_query, query: { id: 3 }}Go to redirect_with_query/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_params, params: { id: 3 }}Go to redirect_with_params/router-linkbr!-- 将 props 传递给路由组件 --router-link :to{ name: nameD, params: { id: 3 }}Go to nameD/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: nameE, params: { id: 3 }}Go to nameE/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: nameF, query: { id: 3 }}Go to nameF/router-link
/templatestyle scoped/style命名视图
script setup langts/scripttemplate
h1LeftSidebar/h1
/templatestyle scoped/stylescript setup langts/scripttemplateh1MainContent/h1
/templatestyle scoped/stylescript setup langts/scripttemplateh1RightSidebar/h1
/templatestyle scoped/style编程式路由
script setup langts
import {useRoute, useRouter} from vue-router;
// 路由对象
const router useRouter()// 路由对象中地方路由表
const toTestA () {router.push(/testA)
}
const toTestAbyName () {router.push({name: nameA})
}
const toTestA1 () {router.push(/ta1)
}
const toTestA2 () {router.push(/ta2)
}const toTestB () {router.push({name: nameB,params: {id: 3}})
}
const toTestC () {router.push({name: nameC,query: {id: 3}})
}
const toBack () {router.back()
}
const route useRoute()
/scripttemplateh1忘记历史等于背叛/h1pstrong当前路由路径span v-textroute.fullPath//strong/p!--使用 router-link 组件进行导航 --!--通过传递 to 来指定链接 --!--router-link 将呈现一个带有正确 href 属性的 a 标签--router-link to/homeGo to Home/router-linknbsp;nbsp;nbsp;nbsp;router-link to/aboutGo to About/router-linknbsp;nbsp;nbsp;nbsp;router-link to/order/3Go to Order/router-linkmain styledisplay: flex; justify-content: space-between; width: 1280px;!--命名视图 --router-view nameLeftSidebar classcontent/router-view classcontent/router-view nameRightSidebar classcontent//mainnbsp;nbsp;nbsp;nbsp;RouterLink to/user/loginGo to UserLogin/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink to/user/detailGo to UserDetail/RouterLinkbr/RouterLink to/testAGo to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /testA}Go to TestA/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta1}Go to TestA alias ta1/RouterLinknbsp;nbsp;nbsp;nbsp;RouterLink :to{path: /ta2}Go to TestA alias ta2/RouterLinkbr/!-- 路由传参 --router-link :to{ name: nameB, params: { id: 3 }}Go to nameB/router-linkrouter-link :to{ name: nameC, query: { id: 3 }}Go to nameC/router-linknbsp;nbsp;nbsp;nbsp;!-- redirect 重定向 --RouterLink :to{path: /test_redirect}Go to test_redirect/RouterLinknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_query, query: { id: 3 }}Go to redirect_with_query/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: redirect_with_params, params: { id: 3 }}Go to redirect_with_params/router-linkbr!-- 将 props 传递给路由组件 --router-link :to{ name: nameD, params: { id: 3 }}Go to nameD/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: nameE, params: { id: 3 }}Go to nameE/router-linknbsp;nbsp;nbsp;nbsp;router-link :to{ name: nameF, query: { id: 3 }}Go to nameF/router-linkhrbutton typebutton clicktoTestATestA/buttonbutton typebutton clicktoTestAbyNameTestAbyName/buttonbutton typebutton clicktoTestA1TestA1/buttonbutton typebutton clicktoTestA2TestA2/buttonbutton typebutton clicktoTestBnameB/buttonbutton typebutton clicktoTestCnameC/buttonbutton typebutton clicktoBackback/button
/templatestyle scoped
.content {display: flex;justify-content: center;width: 1280px;
}
/style7、chap07 ajax fetch axios axios
npm install axios --save获取静态数据 准备 json 格式的的数据文件保存在项目的 public 目录 script setup langts
import axios from axios;const axios_get_books () {axios.get(/books.json).then((response) {console.log(response.data);}).catch((error) {console.log(error);});
}
/scripttemplateh1 clickaxios_get_booksAxiosLocalView/h1
/templatestyle scoped/styleimport {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-router
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import AxiosLocalView from ../../views/chap07/AxiosLocalView.vue;
import LoginView from ../../views/chap07/LoginView.vue;
import IndexView from ../../views/chap07/IndexView.vue;
import UserView from ../../views/chap07/UserView.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{name: AxiosLocalView,path: /AxiosLocalView,component: AxiosLocalView,},{name: login,path: /,component: LoginView,},{name: index,path: /index,component: IndexView,},{name: user,path: /user/:id(\\d),component: UserView,},]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createWebHistory(),routes,
})
export default routeraxios跨域 创建express项目 mkdir express
cd expressnpx --yes --package express-generator express --force --no-viewnpm install
npm start网页访问 npm i nodemon -D修改 package.json 文件 {name: express,version: 0.0.0,private: true,scripts: {start: nodemon ./bin/www},dependencies: {cookie-parser: ~1.4.4,debug: ~2.6.9,express: ~4.16.1,morgan: ~1.9.1},devDependencies: {nodemon: ^3.1.7}
} 修改 vite.config.ts 文件实现跨域代理 import {defineConfig} from vite
import vue from vitejs/plugin-vueconst base_url http://localhost:3000
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),],server: {host: 0.0.0.0,strictPort: true,open: true,proxy: {// 使用 proxy 实例/api: {target: http://localhost:3000,changeOrigin: true,rewrite: (path) path.replace(/^\/api/, api),},}},
}) 编写组件 script setup langts
import axios from axios;const axios_get_books () {// axios.get(http://localhost:3000/api/books)axios.get(/api/books).then((response) {console.log(response.data);}).catch((error) {console.log(error)})
}
/scripttemplateh1 clickaxios_get_booksAxiosRemoteView/h1
/templatestyle scoped/style编写路由 import {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-router
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import AxiosLocalView from ../../views/chap07/AxiosLocalView.vue;
import AxiosRemoteView from ../../views/chap07/AxiosRemoteView.vue;
import LoginView from ../../views/chap07/LoginView.vue;
import IndexView from ../../views/chap07/IndexView.vue;
import UserView from ../../views/chap07/UserView.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{name: AxiosLocalView,path: /AxiosLocalView,component: AxiosLocalView,},{name: AxiosRemoteView,path: /AxiosRemoteView,component: AxiosRemoteView,},{name: login,path: /,component: LoginView,},{name: index,path: /index,component: IndexView,},{name: user,path: /user/:id(\\d),component: UserView,},]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default router路由过度 安装 animate.css 动画 npm install animate.css --save在 main.ts 文件中引入 import animate.css编写路由出口组件 HelloLhz script setup langts/scripttemplate!-- 想要在路由组件上使用转场 并对导航进行动画处理 --router-view v-slot{Component ,route}!--transition namefade modeout-in--transition modeout-in:enter-active-classanimate__animated ${route.meta.transitionIn}:leave-active-classanimate__animated ${route.meta.transitionOut}component :isComponent//transition/router-view
/templatestyle scoped/style编写登录组件 script setup langts
import {reactive} from vue;
import {useRouter} from vue-router;const user reactive({account: ,password: ,
});
const router useRouter();
const onSubmit () {router.push({name: index,query: user});
};
/script
templatediv classform_containerdiv classform_item账号input typetext nameaccount classform_input v-modeluser.account/divdiv classform_item密码input typepassword namepassword classform_input v-modeluser.password/divbutton typebutton clickonSubmit登录/button/div
/templatestyle scoped
.form_container {display: flex;flex-direction: column;justify-content: center;align-content: space-between;width: 300px;
}.form_item {display: flex;flex-direction: row;justify-content: space-between;align-items: center;padding-bottom: 10px;
}.form_input {width: 220px;height: 30px;padding-left: 15px;
}
/style编写登录后的组件 script setup langts
/scripttemplateh1忘记历史等于背叛/h1div!-- 想要在路由组件上使用转场 并对导航进行动画处理 --router-view v-slot{Component ,route}!--transition namefade modeout-in--transition modeout-in:enter-active-classanimate__animated ${route.meta.transitionIn}:leave-active-classanimate__animated ${route.meta.transitionOut}component :isComponent//transition/router-view/div
/templatestyle scoped/style编写路由 import {createMemoryHistory, createWebHistory, createWebHashHistory, createRouter} from vue-router
import NotFoundView from ../../views/chap06/NotFoundView.vue;
import AxiosLocalView from ../../views/chap07/AxiosLocalView.vue;
import AxiosRemoteView from ../../views/chap07/AxiosRemoteView.vue;
import LoginView from ../../views/chap07/LoginView.vue;
import IndexView from ../../views/chap07/IndexView.vue;
import UserView from ../../views/chap07/UserView.vue;const routes [// 处理404{path: /:pathMatch(.*)*, component: NotFoundView},{name: AxiosLocalView,path: /AxiosLocalView,component: AxiosLocalView,},{name: AxiosRemoteView,path: /AxiosRemoteView,component: AxiosRemoteView,},{name: login,path: /,component: LoginView,meta: {requiresAuth: true,transitionIn: animate__zoomIn,transitionOut: animate__zoomOut,},},{name: index,path: /index,component: IndexView,meta: {requiresAuth: true,transitionIn: animate__zoomIn,transitionOut: animate__zoomOut,},},{name: user,path: /user/:id(\\d),component: UserView,},]const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default router8、chap08 piaia 安装pinia npm install piniamain.ts 文件中 引入 pinia import { createApp } from vue
import ./style.css// import router from ./router/chap06/router.ts;
// import router from ./router/chap07/router.ts;
import router from ./router/chap08/router.ts;
import App from ./App.vueimport { createPinia } from pinia;const app createApp(App)
app.use(router)app.mount(#app) 编写状态文件 store.ts import {defineStore} from pinia
import {computed, reactive, ref} from vue;// 你可以任意命名 defineStore() 的返回值但最好使用 store 的名字同时以 use 开头且以 Store 结尾。
// (比如 useUserStoreuseCartStoreuseProductStore)
// 第一个参数是你的应用中 Store 的唯一 ID。
// export const useStore defineStore(main, {
// // 为了完整类型推理推荐使用箭头函数
// state: () {
// return {
// count: 0,
// users: [
// {
// name: user0,
// gender: 0
// },
// {
// name: user1,
// gender: 1
// },
// {
// name: user2,
// gender: 0
// },
// {
// name: user3,
// gender: 1
// },
// {
// name: user4,
// gender: 0
// },
// ]
// }
// },
// getters: {
// getByGender: (state, gender) {
// return state.users.fiter(user user.gender gender.value);
// }
// },
// actions: {
// findByGender: (state, gender) {
// return state.users.fiter(user user.gender gender.value);
// }
// },
// })export const useStore defineStore(main, () {// ref() 和 reactive() 就是 state 属性// computed() 就是 getters// function() 就是 actionsconst count ref(0);const users reactive([{name: user0,gender: 0},{name: user1,gender: 1},{name: user2,gender: 0},{name: user3,gender: 1},{name: user4,gender: 0},]);function increment() {count.value}function updateCount(num) {count.value num;}const gender ref(-1)const persons computed(() {return gender.value -1 ? users : users.filter(user user.gender gender.value)});function updateByGender(sex) {gender.value sex}return {count, increment, updateCount, persons, updateByGender}
});编写视图 script setup langts
import {useStore} from ../../store/chap08/store.ts;
import {storeToRefs} from pinia;const store useStore();
const {count, persons} storeToRefs(store)
const {increment, updateCount,updateByGender} store
/scripttemplatedivh1 v-textcount clickcount/h1h1 v-textcount clickincrement/h1h1 v-textcount clickupdateCount(5)/h1button typebutton clickupdateByGender(-1)红男绿女/buttonbutton typebutton clickupdateByGender(1)精神小伙儿/buttonbutton typebutton clickupdateByGender(0)扒蒜老妹儿/buttontabletheadtrth姓名/thth性别/th/tr/theadtbodytr v-for(person,index) in persons :keyperson.nametd v-textperson.name/tdtd v-textperson.gender 1 ? 精神小伙儿:扒蒜老妹儿/td/tr/tbody/table/div
/templatestyle scoped
table {width: 400px;
}
/style编写路由 import {createRouter, createMemoryHistory} from vue-router;
import LhzA from ../../views/chap08/LhzA.vue;const routes [{path: /,component: LhzA},
]
const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default router9、chap09 less、sass、scss element plus echarts scss 安装sass、scss npm install scss --save-dev
npm install scss-loader --save-dev
npm install sass --save-dev
npm install sass-loader --save-dev编写scss文件 var.scss vite.config.ts文件中配置scss import {defineConfig} from vite
import vue from vitejs/plugin-vueconst base_url http://localhost:3000
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),],server: {host: 0.0.0.0,strictPort: true,open: true,proxy: {// 使用 proxy 实例/api: {target: http://localhost:3000,changeOrigin: true,rewrite: (path) path.replace(/^\/api/, api),},}},css: {preprocessorOptions: {scss: {// additionalData: import ./src/style/var.scss;additionalData: use ./src/style/var.scss as *;,}}}
})
element plus 安装 element plus npm install element-plus --save引入 element plus 完整引入 按需导入 自动导入本配置使用自动加载 vite.config.ts import {defineConfig} from vite
import vue from vitejs/plugin-vue
import AutoImport from unplugin-auto-import/vite
import Components from unplugin-vue-components/vite
import {ElementPlusResolver} from unplugin-vue-components/resolversconst base_url http://localhost:3000
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),AutoImport({resolvers: [ElementPlusResolver()],}),Components({// resolvers: [ElementPlusResolver({importStyle: sass})],resolvers: [ElementPlusResolver()],}),],server: {host: 0.0.0.0,strictPort: true,open: true,proxy: {// 使用 proxy 实例/api: {target: http://localhost:3000,changeOrigin: true,rewrite: (path) path.replace(/^\/api/, api),},}},css: {preprocessorOptions: {scss: {// additionalData: import ./src/style/var.scss;additionalData: use ./src/style/var.scss as *;,}}}
})
echarts 快速入门 !DOCTYPE html
htmlheadmeta charsetutf-8 /titleECharts/title!-- 引入刚刚下载的 ECharts 文件 --script srcecharts.js/script/headbody!-- 为 ECharts 准备一个定义了宽高的 DOM --div idmain stylewidth: 600px;height:400px;/divscript typetext/javascript// 基于准备好的dom初始化echarts实例var myChart echarts.init(document.getElementById(main));// 指定图表的配置项和数据var option {title: {text: ECharts 入门示例},tooltip: {},legend: {data: [销量]},xAxis: {data: [衬衫, 羊毛衫, 雪纺衫, 裤子, 高跟鞋, 袜子]},yAxis: {},series: [{name: 销量,type: bar,data: [5, 20, 36, 10, 10, 20]}]};// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);/script/body
/html安装 echarts npm install echarts --savevue 整合 echarts var.scss文件中配置单个组件高度变量 $chartHeight: 490pxCharBar.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;const chartBar ref()
const attrs useAttrs()
const {charColor} attrs// const chartBar useTemplateRef(chartBar)
function chartBarInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartBar.value, dark);// 指定图表的配置项和数据const option reactive({color: charColor,title: {text: 柱状图},tooltip: {},legend: {data: [销量]},xAxis: {data: [衬衫, 羊毛衫, 雪纺衫, 裤子, 高跟鞋, 袜子]},yAxis: {},series: [{name: 销量,type: bar,data: [5, 20, 36, 10, 10, 20]}]});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartBarInit()
})
/scripttemplatediv idchartBar refchartBar/div
/templatestyle scoped langscss
#chartBar {width: 100%;height: $chartHeight;
}
/style首页布局 IndexView.vue script setup langts
import ChartBar from ./chartBar/ChartBar.vue;
import ChartLine from ./chartLine/ChartLine.vue;
import ChartMap from ./chartMap/ChartMap.vue;
import ChartPie from ./chartPie/ChartPie.vue;
import ChartRadar from ./chartRadar/ChartRadar.vue;
/scripttemplatedivdiv classindex-containerdiv classside-itemdiv classitemchart-bar :charColor#1e9fff//divdiv classitemchart-pie//div/divdiv classside-item styleflex: 0 1 150%div classitemchart-map//div/divdiv classside-itemdiv classitemchart-radar//divdiv classitemchart-line :charColor#1e9fff//div/div/div/div
/templatestyle scoped
.index-container {width: 100%;display: flex;flex-direction: row;justify-content: space-between;align-items: stretch;.side-item {width: 100%;display: flex;flex-direction: column;justify-content: space-between;align-content: stretch;}.item {padding: 10px;}
}
/style柱状图 ChartBar.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;const chartBar ref()
const attrs useAttrs()
const {charColor} attrs// const chartBar useTemplateRef(chartBar)
function chartBarInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartBar.value, dark);// 指定图表的配置项和数据const option reactive({color: charColor,title: {text: 柱状图},tooltip: {},legend: {data: [销量]},xAxis: {data: [衬衫, 羊毛衫, 雪纺衫, 裤子, 高跟鞋, 袜子]},yAxis: {},series: [{name: 销量,type: bar,data: [5, 20, 36, 10, 10, 20]}]});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartBarInit()
})
/scripttemplatediv idchartBar refchartBar/div
/templatestyle scoped langscss
#chartBar {width: 100%;height: $chartHeight;
}
/styleChartBarView.vue script setup langts
import ChartBar from ./ChartBar.vue;
/scripttemplatedivdiv classindex-containerdiv styleflex: 0 1 30%div classitemchart-bar :charColor#dd6b66//div/divdiv styleflex: 0 1 70%div classitemchart-bar :charColor#1e9fff//div/div/divdiv classindex-containerdiv styleflex: 0 1 70%div classitemchart-bar :charColor#16b777//div/divdiv styleflex: 0 1 30%div classitemchart-bar :charColor#a233c6//div/div/div/div
/templatestyle scoped
.index-container {width: 100%;display: flex;flex-direction: row;.item{padding: 10px;}
}
/style折线图 ChartLine.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;const chartLine ref()
const attrs useAttrs()
const {charColor} attrs// const chartBar useTemplateRef(chartBar)
function chartBarInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartLine.value, dark);// 指定图表的配置项和数据const option reactive({color: charColor,title: {text: 折线图},tooltip: {},legend: {data: [pay]},xAxis: {type: category,data: [Mon, Tue, Wed, Thu, Fri, Sat, Sun]},yAxis: {type: value},series: [{name: pay,data: [820, 932, 901, 934, 1290, 1330, 1320],type: line,smooth: true}]});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartBarInit()
})
/scripttemplatediv idchartLine refchartLine/div
/templatestyle scoped langscss
#chartLine {width: 100%;height: $chartHeight;
}
/styleChartLineView.vue script setup langts
import ChartLine from ./ChartLine.vue;
/scripttemplatedivdiv classindex-containerdiv styleflex: 0 1 30%div classitemchart-line :charColor#dd6b66//div/divdiv styleflex: 0 1 70%div classitemchart-line :charColor#1e9fff//div/div/divdiv classindex-containerdiv styleflex: 0 1 70%div classitemchart-line :charColor#16b777//div/divdiv styleflex: 0 1 30%div classitemchart-line :charColor#a233c6//div/div/div/div
/templatestyle scoped
.index-container {width: 100%;display: flex;flex-direction: row;.item{padding: 10px;}
}
/style饼图 ChartPie.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;const chartPie ref()
const attrs useAttrs()// const chartPie useTemplateRef(chartPie)
function chartPieInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartPie.value, dark);// 指定图表的配置项和数据const option reactive({title: {text: Referer of a Website,subtext: Fake Data,left: center},tooltip: {trigger: item},legend: {orient: vertical,left: left},series: [{name: Access From,type: pie,radius: 50%,data: [{value: 1048, name: Search Engine},{value: 735, name: Direct},{value: 580, name: Email},{value: 484, name: Union Ads},{value: 300, name: Video Ads}],emphasis: {itemStyle: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: rgba(0, 0, 0, 0.5)}}}]});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartPieInit()
})
/scripttemplatediv idchartPie refchartPie/div
/templatestyle scoped langscss
#chartPie {width: 100%;height: $chartHeight;
}
/styleChartPieView.vue script setup langts
import ChartPie from ./ChartPie.vue;
/scripttemplatedivdiv classindex-containerdiv styleflex: 0 1 30%div classitemchart-pie//div/divdiv styleflex: 0 1 70%div classitemchart-pie//div/div/divdiv classindex-containerdiv styleflex: 0 1 70%div classitemchart-pie//div/divdiv styleflex: 0 1 30%div classitemchart-pie//div/div/div/div
/templatestyle scoped
.index-container {width: 100%;display: flex;flex-direction: row;.item{padding: 10px;}
}
/style雷达图 ChartRadar.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;const chartRadar ref()
const attrs useAttrs()// const chartRadar useTemplateRef(chartRadar)
function chartRadarInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartRadar.value, dark);// 指定图表的配置项和数据const option reactive({title: {text: Basic Radar Chart},legend: {data: [Allocated Budget, Actual Spending]},radar: {// shape: circle,indicator: [{name: Sales, max: 6500},{name: Administration, max: 16000},{name: Information Technology, max: 30000},{name: Customer Support, max: 38000},{name: Development, max: 52000},{name: Marketing, max: 25000}]},series: [{name: Budget vs spending,type: radar,data: [{value: [4200, 3000, 20000, 35000, 50000, 18000],name: Allocated Budget},{value: [5000, 14000, 28000, 26000, 42000, 21000],name: Actual Spending}]}]});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartRadarInit()
})
/scripttemplatediv idchartRadar refchartRadar/div
/templatestyle scoped langscss
#chartRadar {width: 100%;height: $chartHeight;
}
/styleChartRadarView.vue script setup langts
import ChartRadar from ./ChartRadar.vue;
/scripttemplatedivdiv classindex-containerdiv styleflex: 0 1 30%div classitemchart-radar//div/divdiv styleflex: 0 1 70%div classitemchart-radar//div/div/divdiv classindex-containerdiv styleflex: 0 1 70%div classitemchart-radar//div/divdiv styleflex: 0 1 30%div classitemchart-radar//div/div/div/div
/templatestyle scoped
.index-container {width: 100%;display: flex;flex-direction: row;.item{padding: 10px;}
}
/style地图 提前准备省份json文件和经纬度坐标文件 ChartMap.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;
import china_province from ../../../store/chap09/china_province.json
import china_geo from ../../../store/chap09/china_full.jsonconst chartMap ref()
const attrs useAttrs()
const convertData function (data) {let res [];for (let i 0; i data.length; i) {let geoCoord china_geo.features[i].properties;if (geoCoord) {res.push({name: data[i].name,value: geoCoord.center.concat(data[i].value)});}}return res;
};// const chartMap useTemplateRef(chartMap)
function chartMapInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartMap.value, dark);// 注入地图数据 GeoJson 注意第一个参数为 china 才会显示 海南岛缩略图 其它名字不会echarts.registerMap(china, china_geo);// 指定图表的配置项和数据const option reactive({title: {text: 全国主要城市空气质量 - 百度地图,left: center},tooltip: {trigger: item,formatter: function (params) {// console.log(params);return ${params.data.name}${params.data.value[2]}}},// 地图配置geo: {type: map,// chinaMap 这个参数 为 echarts.registerMap(chinaMap, response); 参数中第一个参数// 注意参数为 china 才会显示 海南岛缩略图 其它名字不会map: china,// 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移可以设置成 scale 或者 move。设置成 true 为都开启roam: true,// 图形上的文本标签可用于说明图形的一些数据信息比如值名称等label: {// 是否显示标签show: true},// 默认缩放比例zoom: 1.1,// 地图中心点坐标// 当前视角的中心点默认使用原始坐标经纬度。如果设置了projection则用投影后的坐标表示。// center: [125.3245, 43.886841]},series: [{geoIndex: 0,type: effectScatter,// 配置何时显示特效// render 绘制完成后显示特效// emphasis 高亮hover的时候显示特效。showEffectOn: render,// data: [{ name: 北京市, value: [116.405285, 39.904989, 9] }],data: convertData(china_province),// 使用地理坐标系通过 geoIndex 指定相应的地理坐标系组件。coordinateSystem: geo,symbolSize: function (param) {// console.log(param[2]);return param[2] / 2},},],// 是视觉映射组件用于进行『视觉编码』也就是将数据映射到视觉元素视觉通道visualMap: {min: 0,max: 50,// 筛选calculable: true}});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartMapInit()
})
/scripttemplatediv idchartMap refchartMap/div
/templatestyle scoped langscss
#chartMap {width: 100%;height: 1000px;
}
/style编写路由 import {createRouter, createMemoryHistory} from vue-router;
import IndexView from ../../views/chap09/IndexView.vue;
import ChartBarView from ../../views/chap09/chartBar/ChartBarView.vue;
import ChartLineView from ../../views/chap09/chartLine/ChartLineView.vue;
import CharPieView from ../../views/chap09/chartPie/ChartPieView.vue;
import ChartRadarView from ../../views/chap09/chartRadar/ChartRadarView.vue;
import ChartMap from ../../views/chap09/chartMap/ChartMap.vue;const routes [{path: /,name: index,component: IndexView},{path: /ChartBarView,name: ChartBarView,component: ChartBarView},{path: /ChartLineView,name: ChartLineView,component: ChartLineView},{path: /CharPieView,name: CharPieView,component: CharPieView},{path: /ChartRadarView,name: ChartRadarView,component: ChartRadarView},{path: /ChartMap,name: ChartMap,component: ChartMap},
]
const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default routerwidth: 100%; display: flex; flex-direction: row; .item{ padding: 10px; } } 地图 提前准备省份json文件和经纬度坐标文件 ChartMap.vue script setup
import * as echarts from echarts;
// import { BarChart } from echarts/charts;
import {ref, reactive, onMounted, useAttrs, useTemplateRef} from vue;
import china_province from ../../../store/chap09/china_province.json
import china_geo from ../../../store/chap09/china_full.jsonconst chartMap ref()
const attrs useAttrs()
const convertData function (data) {let res [];for (let i 0; i data.length; i) {let geoCoord china_geo.features[i].properties;if (geoCoord) {res.push({name: data[i].name,value: geoCoord.center.concat(data[i].value)});}}return res;
};// const chartMap useTemplateRef(chartMap)
function chartMapInit() {// 基于准备好的dom初始化echarts实例const myChart echarts.init(chartMap.value, dark);// 注入地图数据 GeoJson 注意第一个参数为 china 才会显示 海南岛缩略图 其它名字不会echarts.registerMap(china, china_geo);// 指定图表的配置项和数据const option reactive({title: {text: 全国主要城市空气质量 - 百度地图,left: center},tooltip: {trigger: item,formatter: function (params) {// console.log(params);return ${params.data.name}${params.data.value[2]}}},// 地图配置geo: {type: map,// chinaMap 这个参数 为 echarts.registerMap(chinaMap, response); 参数中第一个参数// 注意参数为 china 才会显示 海南岛缩略图 其它名字不会map: china,// 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移可以设置成 scale 或者 move。设置成 true 为都开启roam: true,// 图形上的文本标签可用于说明图形的一些数据信息比如值名称等label: {// 是否显示标签show: true},// 默认缩放比例zoom: 1.1,// 地图中心点坐标// 当前视角的中心点默认使用原始坐标经纬度。如果设置了projection则用投影后的坐标表示。// center: [125.3245, 43.886841]},series: [{geoIndex: 0,type: effectScatter,// 配置何时显示特效// render 绘制完成后显示特效// emphasis 高亮hover的时候显示特效。showEffectOn: render,// data: [{ name: 北京市, value: [116.405285, 39.904989, 9] }],data: convertData(china_province),// 使用地理坐标系通过 geoIndex 指定相应的地理坐标系组件。coordinateSystem: geo,symbolSize: function (param) {// console.log(param[2]);return param[2] / 2},},],// 是视觉映射组件用于进行『视觉编码』也就是将数据映射到视觉元素视觉通道visualMap: {min: 0,max: 50,// 筛选calculable: true}});// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);window.addEventListener(resize, function () {myChart.resize();});
}onMounted(() {chartMapInit()
})
/scripttemplatediv idchartMap refchartMap/div
/templatestyle scoped langscss
#chartMap {width: 100%;height: 1000px;
}
/style编写路由 import {createRouter, createMemoryHistory} from vue-router;
import IndexView from ../../views/chap09/IndexView.vue;
import ChartBarView from ../../views/chap09/chartBar/ChartBarView.vue;
import ChartLineView from ../../views/chap09/chartLine/ChartLineView.vue;
import CharPieView from ../../views/chap09/chartPie/ChartPieView.vue;
import ChartRadarView from ../../views/chap09/chartRadar/ChartRadarView.vue;
import ChartMap from ../../views/chap09/chartMap/ChartMap.vue;const routes [{path: /,name: index,component: IndexView},{path: /ChartBarView,name: ChartBarView,component: ChartBarView},{path: /ChartLineView,name: ChartLineView,component: ChartLineView},{path: /CharPieView,name: CharPieView,component: CharPieView},{path: /ChartRadarView,name: ChartRadarView,component: ChartRadarView},{path: /ChartMap,name: ChartMap,component: ChartMap},
]
const router createRouter({// 4. 内部提供了 history 模式的实现。// memory 模式。createMemoryHistory// hash 模式。createWebHashHistory// html5 模式。createWebHistoryhistory: createMemoryHistory(),routes,
})
export default router