阐述
vue-cli 构建一个工程的时候,发现官方文档还是不够用,需要熟练掌握 es6,而 vue 的全家桶还是都要上的。
Vue CLI 的包名称由vue-cli改成了@vue/cli。 如果你已经全局安装了旧版本的vue-cli(1.x 或 2.x),你需要先通过 npm uninstall vue-cli -g 或 yarn global remove vue-cli
卸载它。
安装新版的脚手 node 也有版本要求,Vue CLI 4.x 需要Node.jsv8.9 或更高版本 (推荐 v10 以上)。
vue全家桶
vue全家桶是基于vue开发必备的也是必学的东西,概括起来就是:
1.vue-cli项目构建工具
2.vue-router路由管理
3.vuex状态管理全局变量
4.axios,http请求工具。
5.UI 框架 element,iview,vant
最常见常用的 vue 全家桶简单的介绍一下,希望可以帮助你了解认识学会 vue 全家桶!
vue-cli
vue-cli 就是快速搭建一个 vue 项目的脚手架工具。
VueCLI是一个官方发布vue.js项目脚手架,使用 VueCLI 可以快速搭建 vue 开发环境,以及对应的 webpack 配置。
1、CLI 是 Command-Line Interface, 翻译为命令行界面, 但是俗称脚手架
2、Vue CLI是一个官方发布 vue.js 项目脚手架
3、使用 vue-cli 可以快速搭建 Vue 开发环境以及对应的 webpack 配置.
关于旧版本
Vue CLI 的包名称由 vue-cli 改成了 @vue/cli
。 如果你已经全局安装了旧版本的 vue-cli (1.x 或 2.x)
,你需要先通过 npm uninstall vue-cli -g
或 yarn global remove vue-cli
卸载它。
脚手架依赖于 node.js
和 webpack
。
Vue CLI 需要 Node.js 8.9 或更高版本 (推荐 8.11.0+)。你可以使用 nvm 或 nvm-windows 在同一台电脑中管理多个 Node 版本。
Vue CLI 的安装
Vue CLI2初始化项目:vue init webpack my-project
Vue CLI3初始化项目:vue create my-project
注意: 下面的默认安装的是 Vue CLI3 的版本,如果需要想按照 Vue CLI2 的方式初始化项目时不可以的。
由于博主的版本过低出现了切换 node 版本、反复安装操作,第二步查看 Vue Cli 需要的node 版本。版本一直请越过反复安装过程。
① 默认安装 vue/cli 脚手架 3
PS C:\Windows\system32> npm install -g @vue/cli npm WARN deprecated [email protected]: The `subscriptions-transport-ws` package is no longer maintained. We recommend you use `graphql-ws` instead. For help migrating Apollo software to `graphql-ws`, see https://www.apollographql.com/docs/apollo-server/data/subscriptions/#switching-from-subscriptions-transport-ws For general help using `graphql-ws`, see https://github.com/enisdenjo/graphql-ws/blob/master/README.md npm WARN deprecated [email protected]: This package has been deprecated and now it only exports makeExecutableSchema.\nAnd it will no longer receive updates.\nWe recommend you to migrate to scoped packages such as @graphql-tools/schema, @graphql-tools/utils and etc.\nCheck out https://www.graphql-tools.com to learn what package you should use instead npm WARN deprecated [email protected]: The functionality provided by the `apollo-cache-control` package is built in to `apollo-server-core` starting with Apollo Server 3. See https://www.apollographql.com/docs/apollo-server/migration/#cachecontrol for details. npm WARN deprecated [email protected]: The `apollo-tracing` package is no longer part of Apollo Server 3. See https://www.apollographql.com/docs/apollo-server/migration/#tracing for details npm WARN deprecated [email protected]: The `graphql-extensions` API has been removed from Apollo Server 3. Use the plugin API instead: https://www.apollographql.com/docs/apollo-server/integrations/plugins/ npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated C:\Program Files\nodejs\vue -> C:\Program Files\nodejs\node_modules\@vue\cli\bin\vue.js > [email protected] postinstall C:\Program Files\nodejs\node_modules\@vue\cli\node_modules\core-js-pure > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js: > https://opencollective.com/core-js > https://patreon.com/zloirock > bitcoin: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > @apollo/[email protected] postinstall C:\Program Files\nodejs\node_modules\@vue\cli\node_modules\@apollo\protobufjs > node scripts/postinstall npm WARN [email protected] requires a peer of encoding@^0.1.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself. + @vue/[email protected] added 880 packages from 531 contributors in 130.475s 结束
② 默认安装失败,解决mode版本问题
安装之后,你就可以在命令行中访问 vue 命令。
检查其版本是否正确:
PS C:\Windows\system32> vue --version You are using Node v11.15.0, but this version of @vue/cli requires Node ^12.0.0 || >= 14.0.0. Please upgrade your Node version. 您使用的是 Node v11.15.0,但是这个版本的 @vue/cli 需要 Node ^12.0.0 || >= 14.0.0。 请升级您的节点版本。 PS C:\Windows\system32>
③ nvm下载太慢问题解决
由于 nvm 默认的下载地址 http://nodejs.org/dist/ 是外国外服务器,国内很慢可以使用淘宝的镜像。
where nvm 找到 nvm 安装路径
找到 settings.txt 文件
将下面这两句话复制到settings.txt,并保存
node_mirror: https://npm.taobao.org/mirrors/node/ npm_mirror: https://npm.taobao.org/mirrors/npm/
④ 安装 Node ^12.0.0
PS C:\Windows\system32> nvm install 12.0.0 Downloading node.js version 12.0.0 (64-bit)... Complete Creating C:\Users\ASUS\AppData\Roaming\nvm\temp Downloading npm version 6.9.0... Complete Installing npm v6.9.0... Installation complete. If you want to use this version, type nvm use 12.0.0 PS C:\Windows\system32> nvm use 12.0.0 Now using node v12.0.0 (64-bit) PS C:\Windows\system32> nvm list 14.17.6 * 12.0.0 (Currently using 64-bit executable) 11.15.0 此版本主项目 PS C:\Windows\system32>
⑤ 从新安装 VueCli 脚手架 3
PS C:\Windows\system32> npm install -g @vue/cli npm WARN deprecated [email protected]: The `subscriptions-transport-ws` package is no longer maintained. We recommend you use `graphql-ws` instead. For help migrating Apollo software to `graphql-ws`, see https://www.apollographql.com/docs/apollo-server/data/subscriptions/#switching-from-subscriptions-transport-ws For general help using `graphql-ws`, see https://github.com/enisdenjo/graphql-ws/blob/master/README.md npm WARN deprecated [email protected]: This package has been deprecated and now it only exports makeExecutableSchema.\nAnd it will no longer receive updates.\nWe recommend you to migrate to scoped packages such as @graphql-tools/schema, @graphql-tools/utils and etc.\nCheck out https://www.graphql-tools.com to learn what package you should use instead npm WARN deprecated [email protected]: The functionality provided by the `apollo-cache-control` package is built in to `apollo-server-core` starting with Apollo Server 3. See https://www.apollographql.com/docs/apollo-server/migration/#cachecontrol for details. npm WARN deprecated [email protected]: The `apollo-tracing` package is no longer part of Apollo Server 3. See https://www.apollographql.com/docs/apollo-server/migration/#tracing for details npm WARN deprecated [email protected]: The `graphql-extensions` API has been removed from Apollo Server 3. Use the plugin API instead: https://www.apollographql.com/docs/apollo-server/integrations/plugins/ npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated C:\Program Files\nodejs\vue -> C:\Program Files\nodejs\node_modules\@vue\cli\bin\vue.js > [email protected] postinstall C:\Program Files\nodejs\node_modules\@vue\cli\node_modules\core-js-pure > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js: > https://opencollective.com/core-js > https://patreon.com/zloirock > bitcoin: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > @apollo/[email protected] postinstall C:\Program Files\nodejs\node_modules\@vue\cli\node_modules\@apollo\protobufjs > node scripts/postinstall npm WARN [email protected] requires a peer of encoding@^0.1.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself. + @vue/[email protected] added 880 packages from 531 contributors in 81.975s 安装结束
查看 vue 版本,及验证是否安装正确。
PS C:\Windows\system32> vue --version @vue/cli 5.0.4 PS C:\Windows\system32>
④ 拉取 2.x 模板 (旧版本)
Vue CLI >= 3 和旧版使用了相同的 vue 命令,所以 Vue CLI 2 (vue-cli) 被覆盖了。
如果你仍然需要使用旧版本的 vue init 功能,你可以全局安装一个桥接工具:
PS C:\Windows\system32> npm install -g @vue/cli-init npm WARN deprecated [email protected]: This package has been deprecated in favour of @vue/cli npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen) npm WARN deprecated [email protected]: this library is no longer supported npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. + @vue/[email protected] added 259 packages from 231 contributors in 38.328s PS C:\Windows\system32>
vue init
的运行效果将会跟 [email protected]
相同。
创建项目提示,原因上面安装已经提示命令都为弃用状态。
PS E:\node> vue init webpack vue-cli2-test Command vue init requires a global addon to be installed. Please run undefined @vue/cli-init and try again. 命令 vue init 需要安装全局插件。 请运行 undefined @vue/cli-init 并重试。 PS E:\node>
⑤ 安装vue指定版本
【前端开发】Vue-CLI4 &Vue-CLI3 与Vue-CLI2 的区别
1、安装:
Vue-CLI2:
npm install -g vue-cli 或 cnpm install -g vue-cli
Vue-CLI最新版本:
npm install -g @vue/cli 或 cnpm install -g @vue/cli
2、卸载
Vue-CLI2:
npm uninstall -g vue-cli 或 cnpm uninstall -g vue-cli
Vue-CLI最新版本:
npm uninstall -g @vue/cli 或 cnpm uninstall -g @vue/cli
指定版本安装
可以安装:2.6.0 版本 npm install -g [email protected] 可以安装:2.6.0 版本 cnpm install -g [email protected].* 卸载vue cnpm uninstall -g vue-cli
cdn 链接
Vue 测试实例 - 菜鸟教程(runoob.com) https://unpkg.com/browse/[email protected]/dist/ 选择vue版本 https://unpkg.com/browse/[email protected]/dist/vue.min.js
⑥ 博主node版本
改 vue 版本
PS C:\WINDOWS\system32> npm install vue-cli -g npm WARN deprecated [email protected]: This package has been deprecated in favour of @vue/cli npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen) npm WARN deprecated [email protected]: this library is no longer supported npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. C:\Program Files\nodejs\vue-init -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue-init C:\Program Files\nodejs\vue-list -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue-list C:\Program Files\nodejs\vue -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue + [email protected] added 244 packages from 229 contributors and updated 1 package in 22.77s PS C:\WINDOWS\system32> vue -V 2.9.6 PS C:\WINDOWS\system32>
如何查看 Vue项 目 vue 的版本号:
如果是用 vue-cli 创建的项目,则找到项目根目录下的 "package.json"
文件。
初始化项目
① vue init命令讲解
用 vue init 命令来初始化项目,具体使用方法如下:
vue init
init:表示要用 vue-cli 来初始化项目
:表示模板名称,vue-cli 官方提供的 5 种模板:
1、webpack:
一个全面的 webpack+vue-loader 的模板,功能包括热加载,linting,检测和CSS扩展。
2、webpack-simple:
一个简单 webpack+vue-loader 的模板,不包含其他功能,让你快速的搭建 vue 的开发环境。
3、browserify:
一个全面的 Browserify+vueify 的模板,功能包括热加载,linting,单元检测。
4、browserify-simple:
一个简单 Browserify+vueify 的模板,不包含其他功能,让你快速的搭建 vue 的开发环境。
5、simple:
一个最简单的单页应用模板。
:标识项目名称,用户根据自己的项目来起名字。
② 项目初始化
在实际开发中,一般都会使用 webpack 这个模板,命令使用如下:
第一步操作:
PS E:\node> vue init webpack vue-cli296 ? Project name (vue-cli296)
Project name:项目名称 ,默认为初始化建项目的名称 vue-cli296,不需要直接回车
第二步操作:
Project description (A Vue.js project)
Project description:项目描述,默认为A Vue.js project,不需要直接回车
Author (cwgqmxy <[email protected]>)
Author:作者,如果有配置 git 的作者,自动会读取。直接回车
第三步操作:
两个选项,Runtime + Compiler 和 Runtime-only:
· Runtime + Compiler: recommended for most users (运行程序+编译器:推荐给大多数用户) · Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specificHTML) are ONLY allowed in .vue files - render functions are required elsewhere (仅运行程序: 比上面那种模式轻大约 6KB min+gzip,但是 template (或任何特定于vue的html)只允许在.vue文件中使用——其他地方用需要 render 函数)
区别
1、runtime-only 比 runtime-compiler 轻 6kb
2、runtime-only 运行更快
3、runtime-only 其实只能识别 render 函数,不能识别 template,.vue 文件中的也是被 vue-template-compiler 翻译成了 render 函数,所以只能在 .vue
里写 template。
两种模式生成的 脚手架 即(代码模板)其实区别只有在 main.js 中,其他都是一样的:
可以发现一个 是用 template + component 而另一个 则是 用 render 函数。
第四步操作:
Install vue-router? (Y/n)
Install vue-router?
是否安装vue的路由插件,需要安装,选择Y
第五步操作:
Use ESLint to lint your code? (Y/n) 输入 Y Pick an ESLint preset:选择分支风格 选项有三个(博主选了第一个) 1.standard(https://github.com/feross/standard) js的标准风格 2.Airbnb(https://github.com/airbnb/javascript) JavaScript最合理的方法,这个github地址说是JavaScript最合理的方法 3.none (configure it yourself) 自己配置
Use ESLint to lint your code?
是否用 ESLint 来限制你的代码错误和风格。不需要输入n,需要选择y,如果是大型团队开发,最好是进行配置。
第六步操作:
Set up unit tests (Y/n)
是否需要安装单元测试工具,不需要输入n,需要选择y
第七步操作:
Setup e2e tests with Nightwatch? (Y/n)
是否安装E2E测试框架NightWatch(E2E,也就是End To End,就是所谓的“用户真实场景”。
第八步操作:
Should we run `npm install` for you after the project has been created? (recommended) (Use arrow keys)
(译:项目创建后是否要为你运行 “npm install”? 这里选择包管理工具)
选项有三个
yes,use npm(使用npm)
yes,use yarn(使用yarn)
no,I will handle that myself(自己配置安装包)
开始创建了项目,初始化完成之后会出现以下信息,表示操作成功。
PS E:\node> vue init webpack vue-cli296 ? Project name vue-cli296 ? Project description A Vue.js project ? Author cwgqmxy <[email protected]> ? Vue build runtime ? Install vue-router? Yes ? Use ESLint to lint your code? Yes ? Pick an ESLint preset Standard ? Set up unit tests No ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recommended) npm vue-cli · Generated "vue-cli296". # Installing project dependencies ... # ======================== npm WARN deprecated [email protected]: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates. npm WARN deprecated [email protected]: This loader has been deprecated. Please use eslint-webpack-plugin npm WARN deprecated [email protected]: Deprecated. Please use https://github.com/webpack-contrib/mini-css-extract-plugin npm WARN deprecated [email protected]: out of support npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated [email protected]: support for ECMAScript is superseded by `uglify-js` as of v3.13.0 npm WARN deprecated [email protected]: Switch to the `bfj` package for fixes and new features! npm WARN deprecated [email protected]: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js. npm WARN deprecated [email protected]: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated [email protected]: flatten is deprecated in favor of utility frameworks such as lodash. npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x. npm WARN deprecated [email protected]: CircularJSON is in maintenance only, flatted is its successor. npm WARN deprecated [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x. npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated > [email protected] postinstall E:\node\vue-cli296\node_modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > [email protected] postinstall E:\node\vue-cli296\node_modules\ejs > node ./postinstall.js Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) > [email protected] postinstall E:\node\vue-cli296\node_modules\es5-ext > node -e "try{require('./_postinstall')}catch(e){}" # # Fatal error in , line 0 # Check failed: U_SUCCESS(status). # # # #FailureMessage Object: 000000E8857BCE10[ ......] / postinstall: info lifecycle [email protected]~postinstall: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.2 (node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\watchpack-chokidar2\node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\webpack-dev-server\node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2022-04-19T08_59_35_781Z-debug.log Running eslint --fix to comply with chosen preset rules... # ======================== > [email protected] lint E:\node\vue-cli296 > eslint --ext .js,.vue src "--fix" # Project initialization finished! # ======================== To get started: cd vue-cli296 npm run dev Documentation can be found at https://vuejs-templates.github.io/webpack PS E:\node>
③ 目录结构详解
④ 运行项目
环境崩溃了,从新装node环境。
npm 是什么东东?
npm其实是Node.js的包管理工具(package manager)。
为啥我们需要一个包管理工具呢?
因为我们在Node.js上开发时,会用到很多别人写的JavaScript代码。
(http://caibaojian.com/npm/all.html)
讲了这么多,npm究竟在哪?
其实npm已经在Node.js安装的时候顺带装好了。我们在命令提示符或者终端输入npm -v,
node 安装适合小白
1 去node官网下载
中文官方网址:http://nodejs.cn/
下载网址:http://nodejs.cn/download/
官方网址:https://nodejs.org/en/
2 下载完成后双击安装包,跳出安装弹窗,点击Next
以下一路 Next
node.js runtime:node 运行环境
orepack manager:npm 包管理
Online documentation shortcuts:在线文件快捷方式
Add to Path:添加路径
corepack manager:核心包管理
不用打钩,如果打了 √ 会把 node 所有的工具都下载,需要很久,以后要什么工具,直接npm下载。
安装好啦
环境路径已经自动设置好了
可以去 cmd 窗口中查看安装 node 和 npm 的版本号。
从新来过
上面环境崩溃了,从新搭建的环境。
PS E:\node> node -v v11.15.0 PS E:\node>
vue-cli 安装
vue-cli是vue官方出品的快速构建单页应用的脚手架,里面集成了webpack,npm,nodejs,babel,vue,vue-router。
PS E:\node> npm install vue-cli -g npm WARN deprecated [email protected]: This package has been deprecated in favour of @vue/cli npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen) npm WARN deprecated [email protected]: this library is no longer supported npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. C:\Program Files\nodejs\vue-init -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue-init C:\Program Files\nodejs\vue -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue C:\Program Files\nodejs\vue-list -> C:\Program Files\nodejs\node_modules\vue-cli\bin\vue-list + [email protected] added 245 packages from 230 contributors in 27.375s PS E:\node>
PS E:\node> vue --version 2.9.6 PS E:\node>
vue-cli 项目初始化
PS E:\node> vue init webpack vue296 ? Project name vue296 ? Project description A Vue.js project ? Author cwgqmxy <[email protected]> ? Vue build standalone ? Install vue-router? Yes ? Use ESLint to lint your code? Yes ? Pick an ESLint preset Standard ? Set up unit tests No ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recommended) npm vue-cli · Generated "vue296". # Installing project dependencies ... # ======================== npm WARN deprecated [email protected]: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates. npm WARN deprecated [email protected]: This loader has been deprecated. Please use eslint-webpack-plugin npm WARN deprecated [email protected]: Deprecated. Please use https://github.com/webpack-contrib/mini-css-extract-plugin npm WARN deprecated [email protected]: out of support npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated [email protected]: support for ECMAScript is superseded by `uglify-js` as of v3.13.0 npm WARN deprecated [email protected]: Switch to the `bfj` package for fixes and new features! npm WARN deprecated [email protected]: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies npm WARN deprecated [email protected]: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js. npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated [email protected]: flatten is deprecated in favor of utility frameworks such as lodash. npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x. npm WARN deprecated [email protected]: CircularJSON is in maintenance only, flatted is its successor. npm WARN deprecated [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x. npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-url#deprecated npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated > [email protected] postinstall E:\node\vue296\node_modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > [email protected] postinstall E:\node\vue296\node_modules\ejs > node ./postinstall.js Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) > [email protected] postinstall E:\node\vue296\node_modules\es5-ext > node -e "try{require('./_postinstall')}catch(e){}" > [email protected] postinstall E:\node\vue296\node_modules\webpack\node_modules\uglifyjs-webpack-plugin > node lib/post_install.js npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.2 (node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\watchpack-chokidar2\node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\webpack-dev-server\node_modules\chokidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) added 1395 packages from 715 contributors in 76.245s Running eslint --fix to comply with chosen preset rules... # ======================== > [email protected] lint E:\node\vue296 > eslint --ext .js,.vue src "--fix" # Project initialization finished! # ======================== To get started: cd vue296 npm run dev Documentation can be found at https://vuejs-templates.github.io/webpack PS E:\node>
cd 命令进入到项目目录
npm run dev
成功页面
package.json
{ "name": "vue296", "version": "1.0.0", "description": "A Vue.js project", "author": "cwgqmxy <[email protected]>", "private": true, "scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "lint": "eslint --ext .js,.vue src", "build": "node build/build.js" }, "dependencies": { "vue": "^2.5.2", "vue-router": "^3.0.1" }, "devDependencies": { "autoprefixer": "^7.1.2", "babel-core": "^6.22.1", "babel-eslint": "^8.2.1", "babel-helper-vue-jsx-merge-props": "^2.0.3", "babel-loader": "^7.1.1", "babel-plugin-syntax-jsx": "^6.18.0", "babel-plugin-transform-runtime": "^6.22.0", "babel-plugin-transform-vue-jsx": "^3.5.0", "babel-preset-env": "^1.3.2", "babel-preset-stage-2": "^6.22.0", "chalk": "^2.0.1", "copy-webpack-plugin": "^4.0.1", "css-loader": "^0.28.0", "eslint": "^4.15.0", "eslint-config-standard": "^10.2.1", "eslint-friendly-formatter": "^3.0.0", "eslint-loader": "^1.7.1", "eslint-plugin-import": "^2.7.0", "eslint-plugin-node": "^5.2.0", "eslint-plugin-promise": "^3.4.0", "eslint-plugin-standard": "^3.0.1", "eslint-plugin-vue": "^4.0.0", "extract-text-webpack-plugin": "^3.0.0", "file-loader": "^1.1.4", "friendly-errors-webpack-plugin": "^1.6.1", "html-webpack-plugin": "^2.30.1", "node-notifier": "^5.1.2", "optimize-css-assets-webpack-plugin": "^3.2.0", "ora": "^1.2.0", "portfinder": "^1.0.13", "postcss-import": "^11.0.0", "postcss-loader": "^2.0.8", "postcss-url": "^7.2.1", "rimraf": "^2.6.0", "semver": "^5.3.0", "shelljs": "^0.7.6", "uglifyjs-webpack-plugin": "^1.1.1", "url-loader": "^0.5.8", "vue-loader": "^13.3.0", "vue-style-loader": "^3.0.1", "vue-template-compiler": "^2.5.2", "webpack": "^3.6.0", "webpack-bundle-analyzer": "^2.9.0", "webpack-dev-server": "^2.9.1", "webpack-merge": "^4.1.0" }, "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" }, "browserslist": [ "> 1%", "last 2 versions", "not ie <= 8" ] }
项目结构
一个 vue-cli 的项目结构如下,其中 src 文件夹是需要掌握,其余了解即可。
文件夹目录如下:
1、build目录(webpack配置)
build 文件主要是 webpack 的配置,目录详情如下:
2、config目录(vue项目配置目录)
config 文件主要是项目相关配置,常用的就是当端口冲突时配置监听端口,打包输出路径及命名等,目录详情如下:
3、node_modules(项目依赖包)
node_modules 里面是项目依赖包,其中包括很多基础依赖,自己也可以根据需要安装其他依赖。安装方法打开命令工具,进入项目目录,输入 npm install [依赖包名称]
,回车。
安装依赖:npm i
在两种情况下我们会自己去安装依赖:
》项目运行缺少该依赖包
》安装插件:如 vuex
PS:有时会安装指定依赖版本,需在依赖包名称后加上版本号信息,
如 npm install [email protected]
src 项目核心文件讲解
核心文件目录前面已经说明了,下面重点讲解 index.html,main.js,App.vue,router
的 index.js,HelloWorld.vue
。
1、index.html(主页)
index.html 为项目的主页,跟其他 html 一样,但一般只定义一个空的根节点,在 main.js 里面定义的实例将挂载在根节点下,内容都通过 vue 组件来填充。
说明如下:
my-vue-demo
2、main.js(入口文件)
main.js 为项目的入口文件,即单入口,主要是引入 vue 框架,根组件及路由设置,并且定义 vue 实例,说明如下:
// 引入vue框架 import Vue from 'vue' // 引入根组件 import App from './App' // 引入路由配置 import router from './router' // 关闭生产模式下给出的提示 Vue.config.productionTip = false // 定义实例 new Vue({ el: '#app', router, components: { App }, template: '' })
3、App.vue(根组件)
一个 vue 页面通常由三部分组成:
模板 (template)
js (script)
样式 (style)
说明如下:
[ template-模板 ]
(1) 模板只能包含一个父节点,也就是说顶层的 div 只能有一个
(如上图,父节点为 #app
的 div,其没有兄弟节点)
(2)是子路由视图插槽,后面的路由页面都显示在此处,相当于 iframe
【script-JS代码】
vue 通常用 es6 来写,用 export default 导出,其下面可以包含数据 data,生命周期 ( mounted 等),方法( methods )等。
【style-CSS样式】
样式通过 style 标签 包裹,默认是影响全局的,如需定义作用域只在该组件下起作用,需在标签上加 scoped,
。
引入外部CSS示例:
4、router(路由配置)
router文件夹下,有一个 index,js 的路由配置文件,
说明如下:
// 引入vue框架 import Vue from 'vue' // 引入vue-router路由依赖 import Router from 'vue-router' // 引入页面组件,命名为HelloWorld import HelloWorld from '@/components/HelloWorld' // 使用路由依赖 Vue.use(Router) // 定义路由配置 export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld } ] })
5、HelloWorld.vue(页面组件)
最熟悉的 HelloWorld 输出,说明如下:
{{ msg }}
网页 CDN 引入 [email protected] 示例
Vue 测试实例 - 菜鸟教程(runoob.com) https://unpkg.com/browse/[email protected]/dist/ 选择vue版本 https://unpkg.com/browse/[email protected]/dist/vue.min.js
Vue入门之Helloworld {{message}}
内部指令
Vue入门之Helloworld 你好请登录后操作你好ABCNot A/B/C
- {{item}}
- {{ index }}. {{ key }} - {{ value }}
本场比赛得分:{{count}}
状态:{{status}}性别:{{sex}}Selected: {{ selected }}
{{message}}{{message}}第一次绑定的值:{{message}}
(1)v-if
你好
(2)v-else
请登录后操作
(3)v-show
你好
(4)v-else-if
ABCNot A/B/C
(5)v-if 与 v-show 的区别
v-if: 在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建,开销较高,在运行时条件很少改变时使用。
v-show:调整css dispaly属性,开销较小,在常频繁地切换时使用。
(6)v-for
(1)基本用法
- {{item}}
(2)对象遍历
参数: 第一个为值,第二个为键名,第三个为索引
- {{ index }}. {{ key }} - {{ value }}
(7)v-text
{{xxx}}
取值有个弊端,当网速很慢或 javascript 出错时,会在页面显示 {{xxx}}
,Vue 提供的 v-text 可以解决这个问题。
{{ message }}
(8)v-html
用于输出 html 代码
(9)v-on
(1)常规用法
// html本场比赛得分:{{count}}// JS data:{ count: 1 }, methods: { add() { this.count++; } }
(2)缩写
指令详情的更多用法参照 v-on 官方 API
(10)v-model
以下的 model 都需要在 data 中声明初始值:
data: { message: 'hello Vue', count: 1, status: [], sex: '男', selected: '' }
(1)input
(2)textarea
(3)checkbox
状态:{{status}}
(4)radio
性别:{{sex}}
(5)select
Selected: {{ selected }}
(11)v-bind
用于处理 html 标签的动态属性,即动态赋值。
(1)常规用法
// html // js data: { imgSrc:'http://liangxinghua.com/uploads/image/20180709/1531106987.png' }
(2)缩写
指令详情的更多用法参照 v-bind 官方 API
(12)v-pre
在模板中跳过 vue 的编译,直接输出原始值,如果在标签中加入 v-pre 就不会输出 vue 中的data 值了。
{{message}}
(13)v-cloak
在 vue 渲染完指定的整个 DOM 后才进行显示。它必须和 CSS 样式一起使用。
// css [v-cloak] { display: none; } // html{{message}}
(14)v-once
只显示 DOM 第一次渲染的值,以后不改变了
第一次绑定的值:{{message}}
生命周期
Vue入门之Helloworld {{message}}
生命周期表格
周期 | 说明 |
---|---|
beforeCreate | 在实例初始化之后,数据观测和事件配置之前被调用 |
created | 在实例创建完成后被立即调用,完成数据观测,属性和方法的运算,初始化事件,$el属性未见 |
beforeMount | 在挂载开始之前被调用:相关的 render 函数首次被调用,只在虚拟DOM生成HTML |
mounted | 在el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用。实例已完成以下的配置:用上面编译好的html内容替换el属性指向的DOM对象。完成模板中的html渲染到html页面中。此过程中进行ajax交互 |
beforeUpdate | 在数据更新之前调用,发生在虚拟DOM重新渲染和打补丁之前。可以在该钩子中进一步地更改状态,不会触发附加的重渲染过程 |
updated | 在由于数据更改导致的虚拟DOM重新渲染和打补丁之后调用。调用时,组件DOM已经更新,所以可以执行依赖于DOM的操作。然而在大多数情况下,应该避免在此期间更改状态,因为这可能会导致更新无限循环。该钩子在服务器端渲染期间不被调用 |
activated | keep-alive 组件激活时调用 |
deactivated | keep-alive 组件停用时调用 |
beforeDestroy | 在实例销毁之前调用。实例仍然完全可用 |
destroyed | 在实例销毁之后调用。调用后,所有的事件监听器会被移除,所有的子实例也会被销毁。该钩子在服务器端渲染期间不被调用 |
生命周期图解
阶段一:创建和挂载
beforecreated:el 和 data 并未初始化 created:完成了 data 数据的初始化,el没有 beforeMount:完成了 el 和 data 初始化 mounted :完成挂载
阶段二:更新
在 chrome console 执行以下命令:
app.message= 'yes !! I do';
beforeUpdate:虚拟 DOM 中根据 data 变化去更新 html
updated:将虚拟 DOM 更新完成的 HTML 更新到页面中
阶段三:销毁
在 chrome console 执行以下命令:
app.$destroy();
beforeDestroy:销毁之前调用
destroyed:销毁之后调用,之后再执行app.message= ‘hello vue’,页面不会同步更新。
常用选项
Vue入门之Helloworld {{message}}价格: {{newPrice}}数字: {{count}}过滤: {{filtera | filterA}}
1、computed 计算属性、改造输出
计算属性:主要是对原数据进行改造输出。
改造输出:包括格式化数据(价格,日期),大小写转换,排序,添加符号。
computed: { newPrice () { return '¥' + this.price + '元'; } }
2、methods 用于绑定 html 中的事件对应的方法
方法属性:用于绑定 html 中的事件对应的方法
methods:{ add (num) { this.count += num; } }
3、watch 数据变化监听器
数据变化监听器:主要用于监测 data 中的数据变化, v-model 生效
watch: { question(val, oldVal) { console.log('new: %s, old: %s', val, oldVal); } }
4、filters 过滤器:通常格式化字符,使用传值
filters: { filterA(value) { return value.toUpperCase(); } }
5、mixins 实现代码重用
混入:用于减少代码污染、减少代码量、实现代码重用
// 额外临时加入时,用于显示日志 var addLog={ updated:function(){ console.log("数据放生变化,变化成"+this.count+"."); } } // 实例化vue var app = new Vue({ // 挂载实例 el:'#app', // 页面数据初始化,字符,对象、数组 data:{ count: 100 }, // 混入 mixins: [addLog] })
6、extends 扩展:对构造器进行扩展
// 扩展 var extendObj ={ created: function(){ console.log("我是被扩展出来的"); } } // 实例化vue var app = new Vue({ // 挂载实例 el:'#app', // 页面数据初始化,字符,对象、数组 data:{ }, // 扩展 extends: extendObj })
实例事件
vue 有实例属性,实例方法,实例事件,前两个跟选项类似,不是很常用,这次只讲实例事件。
Vue入门之Helloworld 数字:{{count}}
1、$on(在构造器外部添加事件)
$on 接收两个参数,第一个参数是调用时的事件名称,第二个参数是一个匿名方法
app.$on('reduce',function(){ console.log('执行了reduce()'); this.count--; });
2、$once(执行一次的事件)
app.$once('reduceOnce',function(){ console.log('只执行一次的方法'); this.count--; });
3、$off(关闭事件)
function off(){ console.log('关闭事件'); app.$off('reduce'); }
4、$emit(事件调用)
function reduce() { // 事件调用 console.log('emit事件调用'); app.$emit('reduce'); }
自定义指令
vue 中的自定义指令通过 Vue.directive
来实现,主要完成内置指令不能完成的一些事情。
Vue入门之自定义指令 {{num}}
1、调试步骤
(1)chrome打开控制器查看
(2)控制台输入“ app.num='通过控制台设置的新name'
”
(3)点击解绑按钮
2、参数说明
el:指令所绑定的元素,可以用来直接操作 DOM
binding: 一个对象,包含指令的很多信息
vnode::Vue编译生成的虚拟节点
3、生命周期
自定义指令有五个生命周期(也叫钩子函数),分别是 bind、inserted、update、componentUpdated、unbind
,说明如下:
1、bind:
只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个绑定时执行一次的初始化动作。
2、inserted:
被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document中)
3、update:
被绑定于元素所在的模板更新时调用,而无论绑定值是否变化。
通过比较更新前后的绑定值,可以忽略不必要的模板更新。
4、componentUpdated:被绑定元素所在模板完成一次更新周期时调用。
5、unbind:只调用一次,指令与元素解绑时调用
组件基础
Vue入门之组件
1、组件注册 component
(1)全局注册
// script Vue.component('button-counter', { data: function () { return { count: 0 } }, template: '' }); new Vue({ el: '#app' }); // html使用
(2)局部注册
// script new Vue({ el: '#app', components:{ "button-inner":{ data: function() { return { inner: 0 } }, template: '' } } }); // html使用
2、props 属性传值
(1)属性取值
// script new Vue({ el: '#app', components:{ "button-props":{ template:`参数1: {{ here }}:---参数2: {{fromHere}}`, props:['here', 'fromHere'] } } }); // html使用
PS:如果属性带 “-”,props
中需要驼峰取值
(2)在构造器向组件传值(v-bind)
// script new Vue({ el: '#app', data: { message: 'hello' }, components:{ "button-props":{ template:`参数1: {{ here }}:---参数2: {{fromHere}}`, props:['here', 'fromHere'] } } }); // html使用
3、父子组件
// script // 子组件 var city = { template:`Sichuan of China` } // 父组件 var parent = { template: ``, components:{ "city": city } } // 实例化 new Vue({ el: '#app', // 定义局部组件 components:{ // 组件注册 "parent": parent } }); // html使用Panda from China!
制作模板
vue 中的模板使用 template 来实现。
Vue入门之组件 我是template标签模板
1、选项模板
2、标签模板
我是template标签模板
3、