大佬们,vue2,帮我看看watch监听怎么优化?

业务:首页有三个模板可以切换,templateId是模板的id,顶部搜索栏滚到一定距离换背景色等,如图所示:
图1
image.png
图2
image.png
请问大佬们:

  1. swich里的代码可以怎么优化?
  2. watch性能怎么优化?我现在的思路就是让watch监听的不要这么频繁。

代码

methods: {
    async reqGetModuleId() {
        const { data, code } = await apiPriceStatus("template_id");
        if (code === 200) this.templateId = data[0].value;
        // templateId为1时的模板逻辑
        if (this.templateId == 1) {
            this.searchBackground = "#FEF9F7";
            this.unwatch()
        }
    }
},
// 滚动事件
onPageScroll(e) {
    this.scrollTop = e.scrollTop;
},
mounted() {
    this.unwatch = this.$watch('scrollTop', (newValue, oldValue) => {
    switch (+this.templateId) {
        case 0:
            if (newValue > 200) {
                this.searchBackground = "#fff";
                this.searchColor = "#ccc";
                this.iconColor = "#ccc";
            } else {
                this.searchBackground = "";
                this.searchColor = "rgba(0,0,0,.1)";
                this.iconColor = "#fff";
            }
            break;
        case 2:
            if (newValue > 400) {
                this.searchBackground = "#fff";
                this.iconColor = "#ccc";
            } else {
                this.searchBackground = "";
                this.iconColor = "#fff";
            }
        }
    })
},
beforeDestroy() {
    this.unwatch()
}

然后再问一下以下代码可以怎么改:

async reqIsLogin() {
    const { data: { isdl, binding } = { isdl: "", binding: "" } } = await apiIsLogin()
    this.isLogin = isdl;
    this.isBinding = binding;
},

最后谢谢各位大佬,祝大佬们生活愉快。

阅读 1.5k
1 个回答

1、给监听函数加个截流(throttle),不要触发那么频繁
2、代码修改:

async reqIsLogin() {
   const { data = {} } = await apiIsLogin()
   const { isdl = '', binding = '' } = data
    this.isLogin = isdl;
    this.isBinding = binding;
}

分开写好理解点,data, isdl, isdl 加上默认值防止为空。(不知道我理解得对不对)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题