Vue首次不触发watch的解决方法

很多时候我们需要Vue首次加载直接触发watch,例如某个自定义组件的样式,会根据某个prop的值进行更新,那么我们就要使用到watch,样式不存在默认值,或者某个样式并不是首次传过来的prop的值所对应的,这样就无法触发watch,导致样式无法更新

一行代码解决问题

watch: {
      sizeType: {
      	// immediate设置为true,就是在首次加载时触发watch
        immediate: true,
        async handler(type) {
          switch (type) {
            case "widthS":
              this.width = 500 + 'px';
              this.height = 300 + 'px';
              break;
            case  "widthM":
              this.width = 1000 + 'px';
              this.height = 600 + 'px';
              break;
            case "heightS":
              this.width = 300 + 'px';
              this.height = 400 + 'px';
              break;
            case "heightM":
              this.width = 600 + 'px';
              this.height = 800 + 'px';
              break;
          }
        }
      }
    }
Logo

前往低代码交流专区

更多推荐