在Vue2中,可以使用计算属性来根据传入的参数动态计算样式。以下是一个示例代码:

父组件:

<template>
  <div>
    <button @click="changePerson(-1)">上一人</button>
    <button @click="changePerson(1)">下一人</button>
    <child :person="currentPerson" />
  </div>
</template>

<script>
import Child from './Child.vue';

export default {
  components: {
    Child
  },
  data() {
    return {
      persons: [
        { name: 'Person 1', sex: 1 },
        { name: 'Person 2', sex: 0 },
        { name: 'Person 3', sex: 1 }
      ],
      currentIndex: 0
    };
  },
  computed: {
    currentPerson() {
      return this.persons[this.currentIndex];
    }
  },
  methods: {
    changePerson(step) {
      this.currentIndex += step;
      if (this.currentIndex < 0) {
        this.currentIndex = 0;
      } else if (this.currentIndex >= this.persons.length) {
        this.currentIndex = this.persons.length - 1;
      }
    }
  }
};
</script>

子组件:

<template>
  <div :class="personClass">{{ person.name }}</div>
</template>

<script>
export default {
  props: {
    person: {
      type: Object,
      required: true
    }
  },
  computed: {
    personClass() {
      return this.person.sex === 1 ? 'male' : 'female';
    }
  }
};
</script>

<style scoped>
.male {
  color: blue;
}
.female {
  color: pink;
}
</style>

在父组件中,我们通过currentPerson计算属性获取当前的人物对象,并将其传递给子组件。在子组件中,使用计算属性personClass根据person对象中的sex字段来动态计算样式类名。当sex为1时,添加male类名,否则添加female类名。

当我们点击上一人或下一人按钮时,会改变父组件中的currentIndex值,进而改变currentPerson计算属性的值,从而触发子组件中的计算属性重新计算样式类名,实现样式的动态更新


原文地址: https://www.cveoy.top/t/topic/hXXS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录