vue学习笔记
Posted 付太
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue学习笔记相关的知识,希望对你有一定的参考价值。
以后都从上往下加了
vue cli2.9配置全局变量 该方法适用于改变整个项目的通用名称,还可以在vuex里配置全局变量,两个全局变量使用的意义不同。
vue cli3.0配置全局变量
1、 cnpm run dev之后希望自动打开浏览器地址
将config下index.js的autoOpenBrowser改为true
2、项目中配置的config/index.js,有dev和production两种环境的配置 以下介绍的是production环境下的webpack配置的理解
// see http://vuejs-templates.github.io/webpack for documentation. var path = require(\'path\') var projectName = \'dist\'; module.exports = { build: { // webpack的编译环境 env: require(\'./prod.env\'), // 编译输入的index.html文件 // __dirname代表当前的目录,config, path.resolve拼接起来就是 // 从config返回上一级,然后进入${projectName}目录,比如dist,然后输出为dist下的index.html index: path.resolve(__dirname, `../${projectName}/index.html`), // 编译完成的项目根目录 assetsRoot: path.resolve(__dirname, `../${projectName}`), // 静态文件目录 assetsSubDirectory: \'static\', // 引入css,js时的路径,相对于html页面,为空,所以打包以后路径为:static/js/xxx.js // 这样项目内部都是相对路径,项目文件夹改名不需要重新打包。 assetsPublicPath: \'\', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: [\'js\', \'css\'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require(\'./dev.env\'), port: 8989, autoOpenBrowser: true, assetsSubDirectory: \'static\', assetsPublicPath: \'/\', proxyTable: { \'/map\': { target: "http://172.11.11.111:8080/", changeOrigin: true }, \'/web/\': { target: \'http://172.22.22.22:8080\', changeOrigin: true } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
vue中的build/webpack.base.conf.js(这里需要配置)
/* 1 配置 webpack 编译入口 2 配置 webpack 输出路径和命名规则 3 配置模块 resolve 规则 4 配置不同类型模块的处理规则 */ var path = require(\'path\') var utils = require(\'./utils\') var config = require(\'../config\') // 获取配置 // vue-loader 配置文件 var vueLoaderConfig = require(\'./vue-loader.conf\') // 给出正确的绝对路径 function resolve(dir) { return path.join(__dirname, \'..\', dir) } module.exports = { // 配置 webpack 编译入口 entry: { app: \'./src/main.js\' }, // 配置 webpack 输出路径和命名规则 output: { // webpack 输出的目标文件夹路径(例如:/dist) path: config.build.assetsRoot, // webpack 输出 bundle 文件命名格式 filename: \'[name].js\', // webpack 编译输出的发布路径 publicPath: process.env.NODE_ENV === \'production\' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, externals: { // 如果需要依赖jquery,这里要配置下 jquery: \'jQuery\' }, // 配置模块 resolve 的规则,当省略文件后缀名时按配置的后缀顺序查找文件 resolve: { extensions: [\'.js\', \'.vue\', \'.json\'], //自动解析确定的拓展名,使导入模块时不带拓展名 // 创建路径别名,一些常用的,路径长的都可以用别名,有了别名之后引用模块更方便,例如 // import Vue from \'vue/dist/vue.common.js\'可以写成 import Vue from \'vue\' alias: { \'vue$\': \'vue/dist/vue.esm.js\', \'@\': resolve(\'src\'), \'example\': resolve(\'example\'), \'components\': \'@/components\', //从这往下对应src里的文件夹,这里需要配置 \'common\': \'@/common\', \'router\': \'@/router\', \'store\': \'@/store\', \'api\': \'@/api\', \'assets\': \'@/assets\', \'constant\': \'@/constant\', \'views\': \'@/views\', \'utils\': \'@/utils\' } }, module: { rules: [{ test: /\\.(js|vue)$/, loader: \'eslint-loader\', enforce: \'pre\', include: [resolve(\'src\'), resolve(\'test\')], options: { formatter: require(\'eslint-friendly-formatter\') } }, { test: /\\.vue$/, loader: \'vue-loader\', options: vueLoaderConfig }, { test: /\\.js$/, loader: \'babel-loader\', include: [resolve(\'src\'), resolve(\'test\')] }, { test: /\\.(png|jpe?g|gif|svg)(\\?.*)?$/, loader: \'url-loader\', options: { limit: 10000, name: utils.assetsPath(\'img/[name].[hash:7].[ext]\') } }, { test: /\\.(mp4|webm|ogg|mp3|wav|flac|aac)(\\?.*)?$/, loader: \'url-loader\', options: { limit: 10000, name: utils.assetsPath(\'media/[name].[hash:7].[ext]\') } }, { test: /\\.(woff2?|eot|ttf|otf)(\\?.*)?$/, loader: \'url-loader\', options: { limit: 10000, name: utils.assetsPath(\'fonts/[name].[hash:7].[ext]\') } } ] } }
webpack.prod.conf.js 生产环境下的配置文件(看看就行,不用配置)
\'use strict\' const path = require(\'path\') const utils = require(\'./utils\') const webpack = require(\'webpack\') const config = require(\'../config\') const merge = require(\'webpack-merge\') // 一个可以合并数组和对象的插件 const baseWebpackConfig = require(\'./webpack.base.conf\') // 用于从webpack生成的bundle中提取文本到特定文件中的插件 // 可以抽取出css,js文件将其与webpack输出的bundle分离 const CopyWebpackPlugin = require(\'copy-webpack-plugin\') const HtmlWebpackPlugin = require(\'html-webpack-plugin\') // 一个用于生成HTML文件并自动注入依赖文件(link/script)的webpack插件 const ExtractTextPlugin = require(\'extract-text-webpack-plugin\') //如果我们想用webpack打包成一个文件,css js分离开,需要这个插件 const OptimizeCSSPlugin = require(\'optimize-css-assets-webpack-plugin\') const UglifyJsPlugin = require(\'uglifyjs-webpack-plugin\') const env = process.env.NODE_ENV === \'testing\' ? require(\'../config/test.env\') : require(\'../config/prod.env\') // 合并基础的webpack配置 const webpackConfig = merge(baseWebpackConfig, { // 配置样式文件的处理规则,使用styleLoaders module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true, usePostCSS: true }) }, devtool: config.build.productionSourceMap ? config.build.devtool : false,// 开启source-map,生产环境下推荐使用cheap-source-map或source-map,后者得到的.map文件体积比较大,但是能够完全还原以前的js代码 output: { path: config.build.assetsRoot,// 编译输出目录 filename: utils.assetsPath(\'js/[name].[chunkhash].js\'),// 编译输出文件名格式 chunkFilename: utils.assetsPath(\'js/[id].[chunkhash].js\')// 没有指定输出名的文件输出的文件名格式 }, // 重新配置插件项 plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html // 位于开发环境下 new webpack.DefinePlugin({ \'process.env\': env }), new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false } }, sourceMap: config.build.productionSourceMap, parallel: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath(\'css/[name].[contenthash].css\'),// 抽离css文件 // Setting the following option to `false` will not extract CSS from codesplit chunks. // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. // It\'s currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it\'s `false`, // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 allChunks: true, }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. // filename 生成网页的HTML名字,可以使用/来控制文件文件的目录结构,最终生成的路径是基于webpac配置的output.path的 new OptimizeCSSPlugin({ cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ // 生成html文件的名字,路径和生产环境下的不同,要与修改后的publickPath相结合,否则开启服务器后页面空白 filename: process.env.NODE_ENV === \'testing\' ? \'index.html\' : config.build.index, // 源文件,路径相对于本文件所在的位置 template: \'index.html\', inject: true, // 要把<script>标签插入到页面哪个标签里(body|true|head|false) minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: \'dependency\' }), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), // enable scope hoisting new webpack.optimize.ModuleConcatenationPlugin(), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: \'vendor\', minChunks (module) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, \'../node_modules\') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: \'manifest\', minChunks: Infinity }), // This instance extracts shared chunks from code splitted chunks and bundles them // in a separate chunk, similar to the vendor chunk // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk new webpack.optimize.CommonsChunkPlugin({ // 为组件分配ID,通过这个插件webpack可以分析和优先考虑使用最多的模块,并为它们分配最小的ID name: \'app\', async: \'vendor-async\', children: true, minChunks: 3 }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, \'../static\'), to: config.build.assetsSubDirectory, ignore: [\'.*\'] } ]) ] }) // gzip模式下需要引入compression插件进行压缩 if (config.build.productionGzip) { const CompressionWebpackPlugin = require(\'compression-webpack-plugin\') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: \'[path].gz[query]\', algorithm: \'gzip\', test: new RegExp( \'\\\\.(\' + config.build.productionGzipExtensions.join(\'|\') + \')$\' ), threshold: 10240, minRatio: 0.8 }) ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require(\'webpack-bundle-analyzer\').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
vue 中build/build.js页(看看就行,基本不用配置)
require(\'./check-versions\')() // 检查 Node 和 npm 版本
// 标明现在是生产环境 process.env.NODE_ENV = \'production\' var ora = require(\'ora\') // 一个很好看的 loading 插件 var rm = require(\'rimraf\') var path = require(\'path\') var chalk = require(\'chalk\') var webpack = require(\'webpack\') var config = require(\'../config\') // 加载 config.js var webpackConfig = require(\'./webpack.prod.conf\') var spinner = ora(\'开始打包生产环境代码,请稍后...\') // 使用 ora 打印出 loading + log spinner.start() // 开始 loading 动画 // 首先删除 打包后文件夹的内容,然后回调函数里面调用 webpack 开始打包 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, function (err, stats) { // 开始 webpack 的编译
// 编译成功的回调函数 spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + \'\\n\\n\') if (stats.hasErrors()) { console.log(chalk.red(\' 构建失败,出现错误!\\n\')) process.exit(1) } console.log(chalk.cyan(\' 打包完成!!!.\\n\')) console.log(chalk.yellow( \' 文件需要在服务端打开。\\n\' + \' 以file:// index.html这种形式打开不起作用\\n\' )) }) })
3、vue 中 BEM样式失效
发现是postcss.js没有配置,需要这样配置下
// https://github.com/michael-ciniawsky/postcss-load-config var salad = require(\'postcss-salad\') module.exports = { "plugins": [ // to edit target browsers: use "browserlist" field in package.json salad({ browser: [\'ie > 9\', \'last 2 version\'], features: { \'bem\': { \'shortcuts\': { \'component\': \'b\', \'modifier\': \'m\', \'descendent\': \'e\' }, \'separators\': { \'descendent\': \'__\', \'modifier\': \'--\' } } } }) ] }
还需要在package.json里安装
"postcss": "^5.2.17",
"postcss-salad": "^1.0.8",
4、一些语法的使用
5、各css背景图片
BEM
postcss
less
module
6、自定义点击事件
7、自定义字体
注入css
@font-face { font-family: \'lcdD\'; src: url(\'~assets/fonts/lcdD.eot\'); src: url(\'~assets/fonts/lcdD.eot?font-spider\') format(\'embedded-opentype\'), url(\'~assets/fonts/lcdD.woff\') format(\'woff\'), url(\'~assets/fonts/lcdD.ttf\') format(\'truetype\'), url(\'~assets/fonts/lcdD.svg\') format(\'svg\'); font-weight: normal; font-style: normal; }
以上是关于vue学习笔记的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段