MST

星途 面试题库

面试题:Vue多选框组与数组绑定的动态数据处理

假设在一个Vue电商项目中,商品有不同的规格(如颜色、尺寸),规格选项通过接口异步获取。获取到的数据格式为[{name: '颜色', options: ['红色', '蓝色', '绿色']}, {name: '尺寸', options: ['S', 'M', 'L']}]。请实现一个功能,当用户选择不同规格的选项时,将选择的结果以数组形式保存并能在页面上正确展示。需阐述实现思路并写出关键代码。
27.8万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 在Vue组件中定义数据属性来存储规格数据和用户选择结果。
  2. 通过created钩子函数调用异步接口获取规格数据。
  3. 为每个规格选项绑定点击事件,在事件处理函数中更新选择结果数组。
  4. 在模板中通过v-for指令展示规格和选项,并根据选择结果动态更新样式以表示选中状态。

关键代码

<template>
  <div>
    <div v-for="(spec, index) in specs" :key="index">
      <p>{{spec.name}}</p>
      <div v-for="(option, optIndex) in spec.options" :key="optIndex"
           :class="{ 'selected': selectedOptions.includes(option) }"
           @click="selectOption(option)">
        {{option}}
      </div>
    </div>
    <p>选择结果: {{ selectedOptions }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      specs: [],
      selectedOptions: []
    };
  },
  created() {
    this.fetchSpecs();
  },
  methods: {
    async fetchSpecs() {
      // 假设这里通过axios获取数据
      const response = await axios.get('/api/specs');
      this.specs = response.data;
    },
    selectOption(option) {
      if (this.selectedOptions.includes(option)) {
        this.selectedOptions = this.selectedOptions.filter(opt => opt!== option);
      } else {
        this.selectedOptions.push(option);
      }
    }
  }
};
</script>

<style scoped>
.selected {
  color: blue;
  text-decoration: underline;
}
</style>

上述代码中,通过fetchSpecs方法获取规格数据,selectOption方法处理用户选择,模板中通过v-for展示规格和选项,并通过class绑定显示选中状态,最后展示选择结果数组。