zoukankan      html  css  js  c++  java
  • Vue实践经验

    多考虑应变

    如果模版中绑定了 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

  • 相关阅读:
    vue-cli项目打包出现空白页和路径错误问题
    Git操作手册
    Atom Editor 插件 atom-less 的使用方法
    Vue搭建
    使绝对定位高宽自适应
    原生JS表单序列化
    前端代码有关搜索引擎的代码
    网页局部打印
    万维网
    浅淡传统企业进入移动互联网的几种方式
  • 原文地址:https://www.cnblogs.com/junhey/p/8869774.html
Copyright © 2011-2022 走看看