【问题标题】:Based on condition how to pass coming props's data or props's default in Vue基于条件如何在Vue中传递即将到来的道具数据或道具的默认值
【发布时间】:2021-09-08 01:56:17
【问题描述】:

在模板中

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

道具

data: {
  screenWidth: window.innerWidth,
},

props: {
 width: {
   type: String,
   default: "35.5rem"
 },
 padding: {
   type: String,
   default: "2rem"
}

在方法中

screenCheckFunc(val){
  if(this.screenWidth > 1024){
       return val
      } else {
        val.default <-- something like this
      }
    }

(在val我想要传递道具)

是否可以使用 func 在else 中传递 props 的默认值?

编辑

抱歉,如果问题不清楚。

<div :style="{width:screenWidth > 1024 ? width : '35.rem' ,padding:screenWidth > 1024 ? padding : '2rem'  }></div>

如果我写三元组,我需要一遍又一遍地写screenWidth &gt; 1024 可以将这个三元组简化为一个函数,所以我只需调用函数并传递道具?

【问题讨论】:

  • 有 2 个默认值提及您的代码。一个在你的道具中,另一个在你的方法中。您需要使用哪一个?
  • @tuhin47 最后一个就是一个例子(val.default)。我想使用(宽度的默认值。例如)或在 props 中声明的任何其他默认值。
  • &lt;div :style="{width:screenCheckFunc(width = 35.5) &gt;&lt;/div&gt; 这个怎么样?
  • 你可以删除其他。 val 默认已经是35.5rem
  • @KarmaBlackshaw 如果我删除 else 它将变为无,因为我写在 style 它会消失并且不会获得默认值。

标签: vue.js vuejs2 vuex


【解决方案1】:

您可以使用访问默认值 this.$options.props['propName'].default。 在您的情况下,您可以通过this.$options.props['width'].default 访问道具width 的默认值

你可以使用这些:

<div :style="screenCheckScreenWidthAndSetStyle()"></div>

screenCheckScreenWidthAndSetStyle() {
   if (this.screenWidth > 1024) {
      return {width: this.width, padding: this.padding};
   } else {
      return {width: this.$options.props['width'].default, padding: this.$options.props['padding'].default};
   }

【讨论】:

    【解决方案2】:

    像这样定义一个对象数组并将其作为道具传递:

    widthSizes:[
      {size:'1024' , width:'35.5'},
      {size:'320' , width:'20'}]
    
    
    screenCheckFunc(val){
    (let width in this.widthSizes){
        if(width.size === val){
            return val.width
        }
    }
    

    【讨论】:

    • 是的,如果它只是 with 但我想传递许多样式中使用的道具,例如填充,高度等......所有默认值都不同,但它们都需要检查屏幕尺寸。当然,我可以检查样式,例如 .. ``` :style="{width:screenWidth > 1024 ? width : '35.5rem', padding: screenWidth > 1024 ? width : '2rem'}``` 等等。因为它的组件有时需要与 css 不同的样式,所以也不能用 css 编写媒体。
    • 我编辑了我的答案,希望对您有所帮助。
    猜你喜欢
    • 2020-05-04
    • 2017-06-20
    • 2018-12-17
    • 2020-01-25
    • 2021-06-05
    • 2020-10-19
    • 2021-12-02
    • 1970-01-01
    • 2018-10-06
    相关资源
    最近更新 更多