【问题标题】:Vue.js: Set an HTML attribute inside v-for based on array dataVue.js:根据数组数据在 v-for 中设置 HTML 属性
【发布时间】:2018-05-24 07:04:57
【问题描述】:

我是 Vue.js 的新手,我想我在它的工作方式上遗漏了一些要点。我正在尝试构建以下内容:

  1. 从 REST API 获取计划列表- 完成
  2. 将计划显示为带有v-for的按钮-完成
  3. 允许用户单击其中一个按钮/计划将其标记为已选择

我在引导列中打印按钮的代码:

<b-col lg="4" class="plan" v-for="plan in plans" :key="plan.id">
<b-button block variant="secondary" v-on:click="pickPlan(plan.id)">
    <p class="price">€ {{plan.price}}</p>
    <p class="plan">{{plan.name}}</p>
</b-button>

我的问题:如果用户单击某个按钮,它会更改该按钮中的属性variant="primary" 并将所有其他属性设置为variant="secondary",我该怎么做?

谢谢。

【问题讨论】:

    标签: javascript vuejs2


    【解决方案1】:

    您可以将variant 属性绑定到您的 Vue 组件上的任何可用数据,或者将其与内联 JavaScript 一起使用,如下所示:

    <b-col lg="4" class="plan" v-for="plan in plans" :key="plan.id">
        <b-button block :variant="plan.id === chosenPlan.id ? 'primary' : 'secondary'" v-on:click="pickPlan(plan.id)">
            <p class="price">€ {{plan.price}}</p>
            <p class="plan">{{plan.name}}</p>
        </b-button>
    </b-col>
    

    然后确保在您的pickPlan(planId) 方法中设置chosenPlan

    【讨论】:

    • 非常感谢您的解决方案易于实施,并且不涉及对plans 数组的摩擦。我最终创建了一种方法来从模板代码中隐藏if 逻辑,如stackoverflow.com/questions/40522634/… 中所述
    • 所以我的最终模板代码是&lt;b-button class="plan" block :variant="planButtonVariant(plan)" v-on:click="pickPlan(plan)"&gt; 和脚本methods: { planButtonVariant: function (plan) { return plan.id === this.chosenPlan.id ? "primary" : "outline-secondary" },
    【解决方案2】:

    解决它的一种方法是扩展计划对象并添加额外的称为变体或选择并使用此属性绑定到模板中的变体属性

    <template>
      <div>
        <b-col lg="4" class="plan" v-for="plan in plans" :key="plan.id">
          <b-button block v-bind:variant="picked ? 'primary' : 'secondary'" v-on:click="pickPlan(id)">
              <p class="price">€ {{plan.price}}</p>
              <p class="plan">{{plan.name}}</p>
          </b-button>
        </b-col>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          plans: [
            { id: 1, name: 'Plan name 1', price: 12.00, picked: false },
            { id: 2, name: 'Plan name 2', price: 24.00, picked: true },
          ]
        }
      },
      methods: {
        pickPlan(id) {
          this.plans = this.plans.map(p => {
            if(p.id === id) {
              return { ...p, picked: true }
            }
            return { ...p, picked: false }
          })
        }
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2016-11-16
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多