You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何封装函数按条件返回传入props或其默认值简化重复判断

可以实现,你原来的思路只差一步调整:直接传入props的运行时值无法拿到定义阶段的默认值,换为传入props的属性名即可读取到默认配置。


方案1:封装函数传props属性名

方法实现

methods: {
  screenCheckFunc(propKey) {
    // 宽度大于1024返回当前props传入值,否则返回props定义的默认值
    return this.screenWidth > 1024 
      ? this[propKey] 
      : this.$options.props[propKey].default
  }
}

模板用法

<div :style="{
  width: screenCheckFunc('width'), 
  padding: screenCheckFunc('padding')
}"></div>

原理:Vue实例的$options.props存储了props的原始定义配置,可以直接读取到你声明的default值。


方案2:封装计算属性(更推荐)

如果需要复用的样式字段固定,直接封装成计算属性代码更简洁:

computed: {
  adaptiveStyle() {
    const isWideScreen = this.screenWidth > 1024
    const propsDefault = this.$options.props
    return {
      width: isWideScreen ? this.width : propsDefault.width.default,
      padding: isWideScreen ? this.padding : propsDefault.padding.default
    }
  }
}

模板直接绑定即可:

<div :style="adaptiveStyle"></div>

注意优化点

记得监听窗口resize事件更新screenWidth,否则窗口大小变化时样式不会自适应更新:

mounted() {
  window.addEventListener('resize', this.updateScreenWidth)
},
beforeUnmount() {
  window.removeEventListener('resize', this.updateScreenWidth)
},
methods: {
  updateScreenWidth() {
    this.screenWidth = window.innerWidth
  }
}

内容的提问来源于stack exchange,提问作者chuluunhvv Nyamjaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:57:04