运行: cnpm i cross-env --save-dev from:https://www.cnblogs.com/linsx/p/9353429.html
View Detailsiframe:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/iframe iframe 内容加载后不改变 使用:onload="this.height=this.contentWindow.document.documentElement.scrollHeight" 例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>自适应高度</h1> <iframe srcdoc='<div style="height: 400px;width: 400px;background: #ddd;"></div>' frameborder="1" scrolling="no" width="100%" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe> <h1>非自适应高度</h1> <iframe srcdoc='<div style="height: 400px;width: 400px;background: #ddd;"></div>' frameborder="1" scrolling="no" width="100%"></iframe> </body> </html> |
iframe 内容加载后改变 定时改变 iframe 高度:
1 2 3 |
setInterval(()=>{ document.querySelector('iframe').height = window.frames[0].document.documentElement.scrollHeight; }, 200); |
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>自适应高度</h1> <iframe srcdoc='<button onclick="this.parentNode.appendChild(this.cloneNode())" style="width: 100px; height: 100px;display: block;"></button>' frameborder="1" scrolling="no" width="100%" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe> <h1>非自适应高度</h1> <iframe srcdoc='<button onclick="this.parentNode.appendChild(this.cloneNode())" style="width: 100px; height: 100px;display: block;"></button>' frameborder="1" scrolling="no" width="100%"></iframe> <script> setInterval(()=>{ document.querySelector('iframe').height = window.frames[0].document.documentElement.scrollHeight; }, 200); </script> </body> </html> |
from:https://www.cnblogs.com/jffun-blog/p/9774121.html
View Details在讲解这些属性之前,假如我们项目的目录的结构如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
### 目录结构如下: demo1 # 工程名 | |--- dist # 打包后生成的目录文件 | |--- node_modules # 所有的依赖包 | |--- app | | |---index | | | |-- views # 存放所有vue页面文件 | | | | |-- parent.vue # 父组件 | | | | |-- child.vue # 子组件 | | | | |-- index.vue | | | |-- components # 存放vue公用的组件 | | | |-- js # 存放js文件的 | | | |-- store # store仓库 | | | | |--- actions.js | | | | |--- mutations.js | | | | |--- state.js | | | | |--- mutations-types.js | | | | |--- index.js | | | |-- app.js # vue入口配置文件 | | | |-- router.js # 路由配置文件 | |--- views | | |-- index.html # html文件 | |--- webpack.config.js # webpack配置文件 | |--- .gitignore | |--- README.md | |--- package.json | |--- .babelrc # babel转码文件 |
具体理解vuex的项目构建可以看这篇文章(https://www.cnblogs.com/tugenhua0707/p/9763177.html). 下面讲解的也是在这篇文章项目结构基础之上进行讲解的。当然如果你对 vuex熟悉的话,就不用看了,直接跳过即可。 注意:下面的代码都是在 webpack+vue+route+vuex 中构建的,可以把下面的代码 复制到该项目中运行即可。 一:理解mapState的使用 当我们的组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余,为了解决这个问题,我们可以使用mapState的辅助函数来帮助我们生成计算属性。 mapState函数返回的是一个对象,我们需要使用一个工具函数将多个对象合并为一个,这样就可以使我们将最终对象传给computed属性。 上面的表述可能会有些模糊,下面我们来做个简单的demo来演示一下: 项目架构如上面示意图所示,先看看 app/index/store/state.js 代码如下:
1 2 3 4 5 |
export default { add: 0, errors: '', counts: 0 }; |
app/index/store/mutations.js 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import * as types from './mutations-types'; export default { [types.ADD] (state, payload) { state.add = payload; }, [types.SETERROR] (state, payload) { state.errors = payload; }, [types.COUNTASYNC] (state, payload) { state.counts = payload; } } |
app/index/store/mutations-types.js 代码如下:
1 2 3 4 5 6 7 8 |
// 新增list export const ADD = 'ADD'; // 设置错误提示 export const SETERROR = 'SETERROR'; // 异步操作count export const COUNTASYNC = 'COUNTASYNC'; |
app/index/store/index.js 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import Vue from 'vue'; import Vuex from 'vuex'; import state from './state'; import mutations from './mutations'; import actions from './actions'; Vue.use(Vuex); Vue.config.devtools = true; export default new Vuex.Store({ state, mutations, actions }); |
app/index/store/actions.js 代码请看github 如上代码所示,现在我们在 app/index/views/parent.vue 这个路由下,在mounted生命周期打印一下 console.log(this);这句代码的时候,如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<template> <div></div> </template> <script type="text/javascript"> export default { data() { return { } }, methods: { }, mounted() { console.log(this); } } </script> |
在浏览器运行后,如下图所示: 如果我们想获取add,或 count的时候,我们需要使用 this.store.state.add或this.store.state.add或this.store.state.count 这样的。 现在我们使用 mapState的话,代码就变成如下了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<template> <div> </div> </template> <script type="text/javascript"> import { mapState } from 'vuex'; export default { data() { return { } }, methods: { }, computed: { ...mapState({ add: state => state.add, counts: state => state.counts }) }, mounted() { console.log(this.add); // 打印出 0 console.log(this.counts); // 打印 0 } } </script> |
如上代码,我们使用 mapState工具函数会将store中的state映射到局部计算属性中。 我们在mounted方法内,直接使用 this.xx 即可使用到对应computed中对应的属性了。也就是 我们使用 this.add 就直接映射到 this.$store.state.add 了 。 当然mapState也可以接受一个数组,如下简单代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
computed: { /* ...mapState({ add: state => state.add, counts: state => state.counts }) */ ...mapState([ 'add', 'counts' ]) }, mounted() { console.log(this); } |
然后我们再在控制台查看输出的this的值,如下: 可以看到,接受数组也是可以的,在mounted生命周期内,我们直接可以使用 this.add 或 this.counts 可以获取到值了。 切记:mapState的属性的时候,一定要和state的属性值相对应,也就是说 state中定义的属性值叫add,那么mapState就叫add,如果我们改成add2的话,就获取不到add的值了,并且add2的值也是 undefined,如下所示: 二:理解mapActions的使用 mapActions 的思想 和 mapState 一样的,下面我们直接看代码的使用方法哦,如下代码: 如果我们不使用 mapActions 的话,我们调用某个方法需要如下代码所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<template> <div></div> </template> <script type="text/javascript"> export default { data() { return { } }, created() { this.test(); }, methods: { test() { // 调用action 需要时使用 this.$store.dispatch 这样的 Promise.all([this.$store.dispatch('commonActionGet', ['getPower', {}])]).then((res) =>{ }); } }, computed: { }, mounted() { } } </script> |
下面我们使用 mapActions的话,代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<template> <div> </div> </template> <script type="text/javascript"> import { mapActions } from 'vuex'; export default { data() { return { } }, created() { this.test(); }, methods: { test() { // 调用 Promise.all([this.commonActionGet(['getPower', {}])]).then((res) => { }); }, // mapActions 使用方法一 将 this.commonActionGet() 映射为 this.$store.dispatch('commonActionGet') ...mapActions(['commonActionGet', 'commonActionGetJSON', 'commonActionPost', 'commonActionPostJSON']) /* // 第二种方式 ...mapActions({ 'commonActionGet': 'commonActionGet', 'commonActionGetJSON': 'commonActionGetJSON', 'commonActionPost': 'commonActionPost', 'commonActionPostJSON': 'commonActionPostJSON' }) */ } } </script> |
三:理解 mapMutations 的使用。 首先我们不使用 mapMutations的话,调用mutations里面的方法,是如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<template> <div> </div> </template> <script type="text/javascript"> export default { data() { return { } }, created() { this.test(); }, methods: { test() { // 调用Mutations 需要时使用 this.$store.commit('ADD', 1) 这样的 Promise.all([this.$store.commit('ADD', 1)]).then(() =>{ console.log(this); }); } } } </script> |
打印 如上 this代码后,看到如下图所示: 想获取值,使用 this.$store.state.add 就等于1了。 下面我们使用 mapMutations话,代码需要改成如下代码: […]
View DetailsmapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } } |
如果你想将一个 getter 属性另取一个名字,使用对象形式:
1 2 3 4 |
mapGetters({ // 映射 `this.doneCount` 为 `store.getters.doneTodosCount` doneCount: 'doneTodosCount' }) |
扩展:ES6展开运算符 定义: .展开运算符允许一个表达式在某处展开。 使用场景 1.展开函数在多个参数的地方使用 。意指用于函数传参 2.多个元素的地方使用,意指用于数组字面量 3.多个边框的地方使用,意指用于解构赋值 注意事项 展开运算符不能用在对象当中,因为目前展开运算符只能在可遍历对象(iterables)可用。 iterables的实现是依靠[Symbol.iterator]函数,而目前只有Array,Set,String内置[Symbol.iterator]方法,而Object尚未内置该方法,因此无法使用展开运算符。不过ES7草案当中已经加入了对象展开运算符特性。 函数调用中使用展开运算符 之前实现方式
1 2 3 4 5 |
function test(a, b, c) { return a + b +c; } var args = [0, 1, 2]; test.apply(null, args);//3 |
如上,我们把args数组当作实参传递给了a,b,c,这边正是利用了Function.prototype.apply的特性。 ES6实现方式
1 2 3 4 5 |
function test(a, b, c) { return a + b + c; } var args = [0, 1, 2]; test(...args);//3 |
使用…展开运算符就可以把args直接传递给test()函数。 数组字面量中使用展开运算符 例如:两个数组合并为一个数组
1 2 |
var arr1=['a','b','c']; var arr2=[...arr1,'d','e']; //['a','b','c','d','e'] |
用在push函数中,可以不用apply()函数合并2个数组
1 2 3 |
var arr1=['a','b','c']; var arr2=['d','e']; arr1.push(...arr2); //['a','b','c','d','e'] |
用于解构赋值 解构赋值也是ES6中的一个特性,而这个展开运算符可以用于部分情景: 展开运算符在解构赋值中的作用跟之前的作用看上去是相反的,将多个数组项组合成了一个新数组。
1 2 3 4 |
let [arg1,arg2,...arg3] = [1, 2, 3, 4]; arg1 //1 arg2 //2 arg3 //['3','4'] |
ps: let [arg1,…arg2,arg3] = [1, 2, 3, 4]; //报错 即:解构赋值中展开运算符只能用在最后: 类数组对象变成数组 展开运算符可以将一个类数组对象变成一个真正的数组对象:
1 |
var obj = document.getElementById("box").getElementsByTagName("li"); |
1 |
<strong>Array.isArray(obj</strong><strong>);//false</strong> |
1 2 3 |
var arr=[...obj]; <strong>Array.isArray(</strong>arr<strong>); //true</strong> |
相关资料:https://vuex.vuejs.org/zh-cn/getters.html https://www.cnblogs.com/mingjiezhang/p/5903026.html http://es6.ruanyifeng.com/#docs/destructuring 作者:smile.轉角 QQ:493177502 from:https://www.cnblogs.com/websmile/p/8328138.html
View Detailscreated:html加载完成之前,执行。执行顺序:父组件-子组件 mounted:html加载完成后执行。执行顺序:子组件-父组件 methods:事件方法执行 watch:watch是去监听一个值的变化,然后执行相对应的函数。 computed:computed是计算属性,也就是依赖其它的属性计算所得出最后的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
export default { name: "draw", data(){ // 定义变量source return { source:new ol.source.Vector({wrapX: false}), } }, props:{ //接收父组件传递过来的参数 map:{ //type:String }, }, mounted(){ //页面初始化方法 if (map==map){ } var vector = new ol.layer.Vector({ source: this.source }); this.map.addLayer(vector); }, watch: { //监听值变化:map值 map:function () { console.log('3333'+this.map); //return this.map console.log('444444'+this.map); var vector = new ol.layer.Vector({ source: this.source }); this.map.addLayer(vector); } }, methods:{ //监听方法 click事件等,执行drawFeatures方法 drawFeatures:function(drawType){} } |
from:https://blog.csdn.net/liudoris/article/details/80255311
View Detailsvue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。 如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。
1 2 3 4 |
const router = new VueRouter({ mode: 'history', routes: [...] }) |
当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看! 不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。 所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。 #后端配置例子 #Apache
1 2 3 4 5 6 7 8 |
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> |
除了 mod_rewrite,你也可以使用 FallbackResource。 #nginx
1 2 3 |
location / { try_files $uri $uri/ /index.html; } |
#原生 Node.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const http = require('http') const fs = require('fs') const httpPort = 80 http.createServer((req, res) => { fs.readFile('index.htm', 'utf-8', (err, content) => { if (err) { console.log('We cannot open "index.htm" file.') } res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) res.end(content) }) }).listen(httpPort, () => { console.log('Server listening on: http://localhost:%s', httpPort) }) |
#基于 Node.js 的 Express 对于 Node.js/Express,请考虑使用 connect-history-api-fallback 中间件。 #Internet Information Services (IIS) 安装 IIS UrlRewrite 在你的网站根目录中创建一个 web.config 文件,内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Handle History Mode and custom 404/500" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration> |
#Caddy
1 2 3 4 |
rewrite { regexp .* to {path} / } |
#Firebase 主机 在你的 firebase.json 中加入:
1 2 3 4 5 6 7 8 9 10 11 |
{ "hosting": { "public": "dist", "rewrites": [ { "source": "**", "destination": "/index.html" } ] } } |
#警告 给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后在给出一个 404 页面。
1 2 3 4 5 6 |
const router = new VueRouter({ mode: 'history', routes: [ { path: '*', component: NotFoundComponent } ] }) |
或者,如果你使用 Node.js 服务器,你可以用服务端路由匹配到来的 URL,并在没有匹配到路由的时候返回 404,以实现回退。更多详情请查阅 Vue 服务端渲染文档。 from:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
View Details1.html
1 2 3 |
<input type="text" @change="specifiName($event)" />//输入框的change事件 <input type="text" @input="specifiName($event)" />//输入框的输入事件 <input type="text" @keyup.enter="specifiName($event)" />//输入框的回车事件 |
2.js
1 2 3 4 5 6 7 8 9 10 |
var vm = new Vue({ el: "#app", methods: { specifiName(e) { var that = this; var val = e.target.value; console.log(val); }, } }); |
from:https://www.cnblogs.com/zhizou/p/10648513.html
View Details一、官方解释: v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。 v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。 相比之下,v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。 一般来说,v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用 v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好。 二、个人理解: 相同点:v-show和v-if都能控制元素的显示和隐藏。 不同点: 实现本质方法不同 v-show本质就是通过设置css中的display设置为none,控制隐藏 v-if是动态的向DOM树内添加或者删除DOM元素 编译的区别 v-show其实就是在控制css v-if切换有一个局部编译/卸载的过程,切换过程中合适地销毁和重建内部的事件监听和子组件 编译的条件 v-show都会编译,初始值为false,只是将display设为none,但它也编译了 v-if初始值为false,就不会编译了 性能 v-show只编译一次,后面其实就是控制css,而v-if不停的销毁和创建,故v-show性能更好一点。 注意点:因为v-show实际是操作display:" "或者none,当css本身有display:none时,v-show无法让显示 总结:如果要频繁切换某节点时,使用v-show(无论true或者false初始都会进行渲染,此后通过css来控制显示隐藏,因此切换开销比较小,初始开销较大),如果不需要频繁切换某节点时,使用v-if(因为懒加载,初始为false时,不会渲染,但是因为它是通过添加和删除dom元素来控制显示和隐藏的,因此初始渲染开销较小,切换开销比较大) from:https://www.cnblogs.com/liutianzeng/p/10978890.html
View Details本篇将简单介绍常用的修饰符。 在上一篇中,介绍了 v-model 和 v-on 简单用法。除了常规用法,这些指令也支持特殊方式绑定方法,以修饰符的方式实现。通常都是在指令后面用小数点“.”连接修饰符名称。 一、v-model的修饰符 v-model 是用于在表单表单元素上创建双向数据绑定的指令。在 <input> 和 <textarea> 上,默认通过监听元素的 input 事件来更新绑定的属性值。 为了能明显的看到绑定属性值的变化,需要在Chrome浏览器中安装Vue Devtools扩展程序。当查看Vue开发的页面时,按F12就可以在开发者工具里看到Vue页签。这里需要注意,只有在引用Vue的开发版本文件,即vue.js文件时,Vue Devtools工具才能正常使用。 .lazy 首先在 vm 对象中增加需要绑定的属性 1 2 3 4 5 6 var vm = new Vue({ el: "#app", data: { input_lazy: "" } }); 在页面中的 input 的元素上添加指令 1 2 3 4 <div class="row"> <h2>v-model.lazy</h2> <input type="text" v-model.lazy="input_lazy" /> </div> 打开页面,开启Vue Devtools,在文本框中输入字符,查看属性值变化 当在文本框输入内容,并且光标焦点没有离开文本框时,属性值没有实时发生变化 而当焦点离开文本框时,属性值发生了变化并与文本框内容保持一致。从这个例子可以看出 .lazy 修饰符延迟了同步更新属性值的时机。即将原本绑定在 input 事件的同步逻辑转变为绑定在 change 事件上。 .number 该修饰符用来将输入内容自动转换成数值。 在 vm 对象里增加一个属性,默认为空字符串 1 2 3 4 5 6 var vm = new Vue({ el: "#app", data: { input_number: "" } }); 在页面的 input 元素上添加指令 1 2 3 4 5 <div class="row"> <h2>v-model.number</h2> <input type="text" v-model.number="input_number" /> <hr /> […]
View DetailsJavaScript规范 目录 类型 对象 数组 字符串 函数 属性 变量 条件表达式和等号 块 注释 空白 逗号 分号 类型转换 命名约定 存取器 构造器 事件 模块 jQuery ES5 兼容性 HTML、CSS、JavaScript分离 使用jsHint 前端工具 类型 原始值: 相当于传值(JavaScript对象都提供了字面量),使用字面量创建对象。 string number boolean null undefined
1 2 3 4 5 6 |
<span class="kwd">var</span><span class="pln"> foo </span><span class="pun">=</span> <span class="lit">1</span><span class="pun">,</span><span class="pln"> bar </span><span class="pun">=</span><span class="pln"> foo</span><span class="pun">;</span><span class="pln"> bar </span><span class="pun">=</span> <span class="lit">9</span><span class="pun">;</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">foo</span><span class="pun">,</span><span class="pln"> bar</span><span class="pun">);</span> <span class="com">// => 1, 9</span> |
复杂类型: 相当于传引用 object array function
1 2 3 4 5 6 |
<span class="kwd">var</span><span class="pln"> foo </span><span class="pun">=</span> <span class="pun">[</span><span class="lit">1</span><span class="pun">,</span> <span class="lit">2</span><span class="pun">],</span><span class="pln"> bar </span><span class="pun">=</span><span class="pln"> foo</span><span class="pun">;</span><span class="pln"> bar</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]</span> <span class="pun">=</span> <span class="lit">9</span><span class="pun">;</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">foo</span><span class="pun">[</span><span class="lit">0</span><span class="pun">],</span><span class="pln"> bar</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]);</span> <span class="com">// => 9, 9</span> |
对象 使用字面值创建对象。
1 2 3 4 5 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> item </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">Object</span><span class="pun">();</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> item </span><span class="pun">=</span> <span class="pun">{};</span> |
不要使用保留字 reserved words 作为键。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> superman </span><span class="pun">=</span> <span class="pun">{</span> <span class="kwd">class</span><span class="pun">:</span> <span class="str">'superhero'</span><span class="pun">,</span> <span class="kwd">default</span><span class="pun">:</span> <span class="pun">{</span><span class="pln"> clark</span><span class="pun">:</span> <span class="str">'kent'</span> <span class="pun">},</span> <span class="kwd">private</span><span class="pun">:</span> <span class="kwd">true</span> <span class="pun">};</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> superman </span><span class="pun">=</span> <span class="pun">{</span><span class="pln"> klass</span><span class="pun">:</span> <span class="str">'superhero'</span><span class="pun">,</span><span class="pln"> defaults</span><span class="pun">:</span> <span class="pun">{</span><span class="pln"> clark</span><span class="pun">:</span> <span class="str">'kent'</span> <span class="pun">},</span><span class="pln"> hidden</span><span class="pun">:</span> <span class="kwd">true</span> <span class="pun">};</span> |
数组 使用字面值创建数组。
1 2 3 4 5 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> items </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">Array</span><span class="pun">();</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> items </span><span class="pun">=</span> <span class="pun">[];</span> |
如果你不知道数组的长度,使用push。
1 2 3 4 5 6 7 |
<span class="kwd">var</span><span class="pln"> someStack </span><span class="pun">=</span> <span class="pun">[];</span> <span class="com">// bad</span><span class="pln"> someStack</span><span class="pun">[</span><span class="pln">someStack</span><span class="pun">.</span><span class="pln">length</span><span class="pun">]</span> <span class="pun">=</span> <span class="str">'abracadabra'</span><span class="pun">;</span> <span class="com">// good</span><span class="pln"> someStack</span><span class="pun">.</span><span class="pln">push</span><span class="pun">(</span><span class="str">'abracadabra'</span><span class="pun">);</span> |
当你需要拷贝数组时使用slice. jsPerf。
1 2 3 4 5 6 7 8 9 10 11 |
<span class="kwd">var</span><span class="pln"> len </span><span class="pun">=</span><span class="pln"> items</span><span class="pun">.</span><span class="pln">length</span><span class="pun">,</span><span class="pln"> itemsCopy </span><span class="pun">=</span> <span class="pun">[],</span><span class="pln"> i</span><span class="pun">;</span> <span class="com">// bad</span> <span class="kwd">for</span> <span class="pun">(</span><span class="pln">i </span><span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun"><</span><span class="pln"> len</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span> <span class="pun">{</span><span class="pln"> itemsCopy</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span> <span class="pun">=</span><span class="pln"> items</span><span class="pun">[</span><span class="pln">i</span><span class="pun">];</span> <span class="pun">}</span> <span class="com">// good</span><span class="pln"> itemsCopy </span><span class="pun">=</span><span class="pln"> items</span><span class="pun">.</span><span class="pln">slice</span><span class="pun">();</span> |
使用slice将类数组的对象转成数组。
1 2 3 4 |
<span class="kwd">function</span><span class="pln"> trigger</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">var</span><span class="pln"> args </span><span class="pun">=</span> <span class="pun">[].</span><span class="pln">slice</span><span class="pun">.</span><span class="pln">apply</span><span class="pun">(</span><span class="pln">arguments</span><span class="pun">);</span> <span class="pun">...</span> <span class="pun">}</span> |
字符串 对字符串使用单引号 "(因为大多时候我们的字符串。特别html会出现")。
1 2 3 4 5 6 7 8 9 10 11 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span> <span class="str">"Bob Parr"</span><span class="pun">;</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span> <span class="str">'Bob Parr'</span><span class="pun">;</span> <span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> fullName </span><span class="pun">=</span> <span class="str">"Bob "</span> <span class="pun">+</span> <span class="kwd">this</span><span class="pun">.</span><span class="pln">lastName</span><span class="pun">;</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> fullName </span><span class="pun">=</span> <span class="str">'Bob '</span> <span class="pun">+</span> <span class="kwd">this</span><span class="pun">.</span><span class="pln">lastName</span><span class="pun">;</span> |
超过80(也有规定140的,项目具体可制定)个字符的字符串应该使用字符串连接换行。 注: 如果过度使用,长字符串连接可能会对性能有影响。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> errorMessage </span><span class="pun">=</span> <span class="str">'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'</span><span class="pun">;</span> <span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> errorMessage </span><span class="pun">=</span> <span class="str">'This is a super long error that \ was thrown because of Batman. \ When you stop to think about \ how Batman had anything to do \ with this, you would get nowhere \ fast.'</span><span class="pun">;</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> errorMessage </span><span class="pun">=</span> <span class="str">'This is a super long error that '</span> <span class="pun">+</span> <span class="str">'was thrown because of Batman.'</span> <span class="pun">+</span> <span class="str">'When you stop to think about '</span> <span class="pun">+</span> <span class="str">'how Batman had anything to do '</span> <span class="pun">+</span> <span class="str">'with this, you would get nowhere '</span> <span class="pun">+</span> <span class="str">'fast.'</span><span class="pun">;</span> |
编程时使用join而不是字符串连接来构建字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<span class="kwd">var</span><span class="pln"> items</span><span class="pun">,</span><span class="pln"> messages</span><span class="pun">,</span><span class="pln"> length</span><span class="pun">,</span><span class="pln"> i</span><span class="pun">;</span><span class="pln"> messages </span><span class="pun">=</span> <span class="pun">[{</span><span class="pln"> state</span><span class="pun">:</span> <span class="str">'success'</span><span class="pun">,</span><span class="pln"> message</span><span class="pun">:</span> <span class="str">'This one worked.'</span> <span class="pun">},{</span><span class="pln"> state</span><span class="pun">:</span> <span class="str">'success'</span><span class="pun">,</span><span class="pln"> message</span><span class="pun">:</span> <span class="str">'This one worked as well.'</span> <span class="pun">},{</span><span class="pln"> state</span><span class="pun">:</span> <span class="str">'error'</span><span class="pun">,</span><span class="pln"> message</span><span class="pun">:</span> <span class="str">'This one did not work.'</span> <span class="pun">}];</span><span class="pln"> length </span><span class="pun">=</span><span class="pln"> messages</span><span class="pun">.</span><span class="pln">length</span><span class="pun">;</span> <span class="com">// bad</span> <span class="kwd">function</span><span class="pln"> inbox</span><span class="pun">(</span><span class="pln">messages</span><span class="pun">)</span> <span class="pun">{</span><span class="pln"> items </span><span class="pun">=</span> <span class="str">'<ul>'</span><span class="pun">;</span> <span class="kwd">for</span> <span class="pun">(</span><span class="pln">i </span><span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun"><</span><span class="pln"> length</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span> <span class="pun">{</span><span class="pln"> items </span><span class="pun">+=</span> <span class="str">'<li>'</span> <span class="pun">+</span><span class="pln"> messages</span><span class="pun">[</span><span class="pln">i</span><span class="pun">].</span><span class="pln">message </span><span class="pun">+</span> <span class="str">'</li>'</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">return</span><span class="pln"> items </span><span class="pun">+</span> <span class="str">'</ul>'</span><span class="pun">;</span> <span class="pun">}</span> <span class="com">// good</span> <span class="kwd">function</span><span class="pln"> inbox</span><span class="pun">(</span><span class="pln">messages</span><span class="pun">)</span> <span class="pun">{</span><span class="pln"> items </span><span class="pun">=</span> <span class="pun">[];</span> <span class="kwd">for</span> <span class="pun">(</span><span class="pln">i </span><span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun"><</span><span class="pln"> length</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span> <span class="pun">{</span><span class="pln"> items</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span> <span class="pun">=</span><span class="pln"> messages</span><span class="pun">[</span><span class="pln">i</span><span class="pun">].</span><span class="pln">message</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">return</span> <span class="str">'<ul><li>'</span> <span class="pun">+</span><span class="pln"> items</span><span class="pun">.</span><span class="pln">join</span><span class="pun">(</span><span class="str">'</li><li>'</span><span class="pun">)</span> <span class="pun">+</span> <span class="str">'</li></ul>'</span><span class="pun">;</span> <span class="pun">}</span> |
函数 函数表达式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<span class="com">// 匿名函数表达式</span> <span class="kwd">var</span><span class="pln"> anonymous </span><span class="pun">=</span> <span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">true</span><span class="pun">;</span> <span class="pun">};</span> <span class="com">// 有名函数表达式</span> <span class="kwd">var</span><span class="pln"> named </span><span class="pun">=</span> <span class="kwd">function</span><span class="pln"> named</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">true</span><span class="pun">;</span> <span class="pun">};</span> <span class="com">// 立即调用函数表达式</span> <span class="pun">(</span><span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="str">'Welcome to the Internet. Please follow me.'</span><span class="pun">);</span> <span class="pun">})();</span> |
绝对不要在一个非函数块里声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但是它们解析不同。 注: ECMA-262定义把块定义为一组语句,函数声明不是一个语句。阅读ECMA-262对这个问题的说明。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span class="com">// bad</span> <span class="kwd">if</span> <span class="pun">(</span><span class="pln">currentUser</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">function</span><span class="pln"> test</span><span class="pun">()</span> <span class="pun">{</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="str">'Nope.'</span><span class="pun">);</span> <span class="pun">}</span> <span class="pun">}</span> <span class="com">// good</span> <span class="kwd">if</span> <span class="pun">(</span><span class="pln">currentUser</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">var</span><span class="pln"> test </span><span class="pun">=</span> <span class="kwd">function</span><span class="pln"> test</span><span class="pun">()</span> <span class="pun">{</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="str">'Yup.'</span><span class="pun">);</span> <span class="pun">};</span> <span class="pun">}</span> |
绝对不要把参数命名为 arguments, 这将会逾越函数作用域内传过来的 arguments 对象。
1 2 3 4 5 6 7 8 9 |
<span class="com">// bad</span> <span class="kwd">function</span><span class="pln"> nope</span><span class="pun">(</span><span class="pln">name</span><span class="pun">,</span><span class="pln"> options</span><span class="pun">,</span><span class="pln"> arguments</span><span class="pun">)</span> <span class="pun">{</span> <span class="com">// ...stuff...</span> <span class="pun">}</span> <span class="com">// good</span> <span class="kwd">function</span><span class="pln"> yup</span><span class="pun">(</span><span class="pln">name</span><span class="pun">,</span><span class="pln"> options</span><span class="pun">,</span><span class="pln"> args</span><span class="pun">)</span> <span class="pun">{</span> <span class="com">// ...stuff...</span> <span class="pun">}</span> |
属性 当使用变量和特殊非法变量名时,访问属性时可以使用中括号(. 优先)。
1 2 3 4 5 6 7 8 9 10 |
<span class="kwd">var</span><span class="pln"> luke </span><span class="pun">=</span> <span class="pun">{</span><span class="pln"> jedi</span><span class="pun">:</span> <span class="kwd">true</span><span class="pun">,</span><span class="pln"> age</span><span class="pun">:</span> <span class="lit">28</span> <span class="pun">};</span> <span class="kwd">function</span><span class="pln"> getProp</span><span class="pun">(</span><span class="pln">prop</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">return</span><span class="pln"> luke</span><span class="pun">[</span><span class="pln">prop</span><span class="pun">];</span> <span class="pun">}</span> <span class="kwd">var</span><span class="pln"> isJedi </span><span class="pun">=</span><span class="pln"> getProp</span><span class="pun">(</span><span class="str">'jedi'</span><span class="pun">);</span> |
变量 总是使用 var 来声明变量,如果不这么做将导致产生全局变量,我们要避免污染全局命名空间。
1 2 3 4 5 |
<span class="com">// bad</span><span class="pln"> superPower </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">SuperPower</span><span class="pun">();</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> superPower </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">SuperPower</span><span class="pun">();</span> |
使用一个 var 以及新行声明多个变量,缩进4个空格。
1 2 3 4 5 6 7 8 9 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> items </span><span class="pun">=</span><span class="pln"> getItems</span><span class="pun">();</span> <span class="kwd">var</span><span class="pln"> goSportsTeam </span><span class="pun">=</span> <span class="kwd">true</span><span class="pun">;</span> <span class="kwd">var</span><span class="pln"> dragonball </span><span class="pun">=</span> <span class="str">'z'</span><span class="pun">;</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> items </span><span class="pun">=</span><span class="pln"> getItems</span><span class="pun">(),</span><span class="pln"> goSportsTeam </span><span class="pun">=</span> <span class="kwd">true</span><span class="pun">,</span><span class="pln"> dragonball </span><span class="pun">=</span> <span class="str">'z'</span><span class="pun">;</span> |
最后再声明未赋值的变量,当你想引用之前已赋值变量的时候很有用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> i</span><span class="pun">,</span><span class="pln"> len</span><span class="pun">,</span><span class="pln"> dragonball</span><span class="pun">,</span><span class="pln"> items </span><span class="pun">=</span><span class="pln"> getItems</span><span class="pun">(),</span><span class="pln"> goSportsTeam </span><span class="pun">=</span> <span class="kwd">true</span><span class="pun">;</span> <span class="com">// bad</span> <span class="kwd">var</span><span class="pln"> i</span><span class="pun">,</span><span class="pln"> items </span><span class="pun">=</span><span class="pln"> getItems</span><span class="pun">(),</span><span class="pln"> dragonball</span><span class="pun">,</span><span class="pln"> goSportsTeam </span><span class="pun">=</span> <span class="kwd">true</span><span class="pun">,</span><span class="pln"> len</span><span class="pun">;</span> <span class="com">// good</span> <span class="kwd">var</span><span class="pln"> items </span><span class="pun">=</span><span class="pln"> getItems</span><span class="pun">(),</span><span class="pln"> goSportsTeam </span><span class="pun">=</span> <span class="kwd">true</span><span class="pun">,</span><span class="pln"> dragonball</span><span class="pun">,</span><span class="pln"> length</span><span class="pun">,</span><span class="pln"> i</span><span class="pun">;</span> |
在作用域顶部声明变量,避免变量声明和赋值引起的相关问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<span class="com">// bad</span> <span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span><span class="pln"> test</span><span class="pun">();</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="str">'doing stuff..'</span><span class="pun">);</span> <span class="com">//..other stuff..</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span><span class="pln"> getName</span><span class="pun">();</span> <span class="kwd">if</span> <span class="pun">(</span><span class="pln">name </span><span class="pun">===</span> <span class="str">'test'</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">false</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">return</span><span class="pln"> name</span><span class="pun">;</span> <span class="pun">}</span> <span class="com">// good</span> <span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span><span class="pln"> getName</span><span class="pun">();</span><span class="pln"> test</span><span class="pun">();</span><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="str">'doing stuff..'</span><span class="pun">);</span> <span class="com">//..other stuff..</span> <span class="kwd">if</span> <span class="pun">(</span><span class="pln">name </span><span class="pun">===</span> <span class="str">'test'</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">false</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">return</span><span class="pln"> name</span><span class="pun">;</span> <span class="pun">}</span> <span class="com">// bad</span> <span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">if</span> <span class="pun">(!</span><span class="pln">arguments</span><span class="pun">.</span><span class="pln">length</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">false</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span><span class="pln"> getName</span><span class="pun">();</span> <span class="kwd">return</span> <span class="kwd">true</span><span class="pun">;</span> <span class="pun">}</span> <span class="com">// good</span> <span class="kwd">function</span><span class="pun">()</span> <span class="pun">{</span> <span class="kwd">var</span><span class="pln"> name </span><span class="pun">=</span><span class="pln"> getName</span><span class="pun">();</span> <span class="kwd">if</span> <span class="pun">(!</span><span class="pln">arguments</span><span class="pun">.</span><span class="pln">length</span><span class="pun">)</span> <span class="pun">{</span> <span class="kwd">return</span> <span class="kwd">false</span><span class="pun">;</span> <span class="pun">}</span> <span class="kwd">return</span> <span class="kwd">true</span><span class="pun">;</span> <span class="pun">}</span> |
[…]
View Details