vue开发技巧

很有用的 Vue 开发技巧

 

1. 路由参数解耦

通常在组件中使用路由参数,大多数人会做以下事情。

export default {
    methods: {
        getParamsId() {
            return this.$route.params.id
        }
    }
}

在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性。

正确的做法是通过 props 来解耦。

const router = new VueRouter({
    routes: [{
        path:  /user/:id ,
        component: User,
        props: true
    }]
})

将路由的 props 属性设置为 true 后,组件内部可以通过 props 接收 params 参数。

export default {
    props: [ id ],
    methods: {
        getParamsId() {
            return this.id
        }
    }
}

2. watch的高级使用

触发监听器执行多个方法 使用数组,您可以设置多个形式,包括字符串、函数、对象。

复制代码
export default {
    data: {
        name:  Joe
    },
    watch: {
        name: [
            sayName1 ,
            function(newVal, oldVal) {
                this.sayName2()
            },
            {
                handler:  sayName3 ,
                immaediate: true
            }
        ]
    },
    methods: {
        sayName1() {
            console.log( sayName1==> , this.name)
        },
        sayName2() {
            console.log( sayName2==> , this.name)
        },
        sayName3() {
            console.log( sayName3==> , this.name)
        }
    }
}
复制代码

3. watch监听多个变量

watch 本身不能监听多个变量。但是,我们可以通过返回具有计算属性的对象然后监听该对象来“监听多个变量”。

复制代码
export default {
    data() {
        return {
            msg1:  apple ,
            msg2:  banana
        }
    },
    compouted: {
        msgObj() {
            const { msg1, msg2 } = this
            return {
                msg1,
                msg2
            }
        }
    },
    watch: {
        msgObj: {
            handler(newVal, oldVal) {
                if (newVal.msg1 != oldVal.msg1) {
                    console.log( msg1 is change )
                }
                if (newVal.msg2 != oldVal.msg2) {
                    console.log( msg2 is change )
                }
            },
            deep: true
        }
    }
}
复制代码

4. 程序化事件监听器

例如,在页面挂载时定义一个定时器,需要在页面销毁时清除定时器。这似乎不是问题。但仔细观察,this.timer 的唯一目的是能够在 beforeDestroy 中获取计时器编号,否则是无用的。

复制代码
export default {
    mounted() {
        this.timer = setInterval(() => {
            console.log(Date.now())
        }, 1000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}
复制代码

如果可能,最好只访问生命周期挂钩。这不是一个严重的问题,但可以认为是混乱。

我们可以通过使用 $on 或 $once 监听页面生命周期销毁来解决这个问题:

复制代码
export default {
    mounted() {
        this.creatInterval( hello )
        this.creatInterval( world )
    },
    creatInterval(msg) {
        let timer = setInterval(() => {
            console.log(msg)
        }, 1000)
        this.$once( hook:beforeDestroy , function() {
            clearInterval(timer)
        })
    }
}

复制代码

 

posted @   lijun12138  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2022-05-18 js数组方法splice删除不彻底
2022-05-18 webpack5转化es6代码后,立即执行函数依旧是箭头函数
点击右上角即可分享
微信分享提示