代码改变世界

Vue实践经验

2018-03-17 20:20  @疯狂的迈步  阅读(253)  评论(0编辑  收藏  举报

多考虑应变

如果模版中绑定了 obj.xx 时,需要注意 obj 是否是异步数据,默认值是否为 null。安全起见,可在组件最外层加 v-if 判断。

<template>
    <div v-if="!!obj">
        <p>{{obj.name}}</p>
        <p>{{obj.age}}</p>
    </div>
</template>
<script>
export default {
    data() {
        return {
            obj: null
        }
    }
}
</script>

this 引用

在组件作用域内使用箭头函数可以保证 this 永远指向组件本身。


// bad
export default {
    data() {
        return {
            msg: 'hello'
        }
    },
    methods: {
        hello() {
            setTimeout(function() {
                console.log(this.msg) // this 指向 window
            })
        }
    }
}
// good
export default {
    data() {
        return {
            msg: 'hello'
        }
    },
    methods: {
        hello() {
            setTimeout(() => {
                console.log(this.msg) // this 指向组件
            })
        }
    }
}

释放资源

善用 destory 释放原生事件、第三方组件、全局事件总线等。

import bus from 'event-bus'
import plugin from 'plugin'
export default {
    // ...
    created() {
        bus.$on('hello', this.hello) // 注册全局事件
        window.addEventListener('resize', this.onResize) // DOM 事件
        plugin.init() // 第三方组件初始化
    },
    destoryed() {
        bus.$off('hello', this.hello)
        window.removeEventListener('resize', this.onResize)
        plugin.destory()
    }
}

初始化,如Props

布尔属性默认值为 false 可以省略
数组最好声明默认值 [],保证数据请求成功前模版里的 v-for 不会出错
对象也需要注意是否声明了默认值 {},避免模版中使用 obj.xx 报错

{
    props: {
        visible: Boolen, // 默认即为 false
        data: Array,     // 需要进行非空判断
        data2: {         // 可安全使用 v-for
            type: Array,
            default: []
        },
        obj: Object,     // 需要进行非空判断
        obj2: {          // 可安全使用 obj.xx
            type: Object,
            default() {
                return {}
            }
        }
    }
}

原文:https://github.com/junhey/studyNotes/issues/30