可以通过监听父组件传递的参数变化,然后在子组件中更新样式。具体代码如下:

父组件:

<template>
  <div>
    <button @click="changePerson">切换人物</button>
    <child-component :person="currentPerson"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      currentPerson: {
        name: 'John',
        sex: 1
      }
    }
  },
  methods: {
    changePerson() {
      // 切换人物
      this.currentPerson = {
        name: 'Tom',
        sex: 0
      }
    }
  }
}
</script>

子组件:

<template>
  <div :class="{'male': person.sex === 1, 'female': person.sex === 0}">
    {{ person.name }}
  </div>
</template>

<script>
export default {
  props: ['person'],
  watch: {
    person: {
      handler() {
        // 监听父组件传递的参数变化,更新样式
        this.updateStyle()
      },
      immediate: true
    }
  },
  methods: {
    updateStyle() {
      // 更新样式
      // ...
    }
  }
}
</script>

<style>
.male {
  color: blue;
}

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

在子组件中使用:class绑定样式,根据person.sex的值来动态切换类名,从而改变样式。通过watch监听父组件传递的参数变化,并在handler中调用updateStyle方法来更新样式。在子组件的样式中定义不同的类名对应不同的样式。当切换人物时,父组件的currentPerson变化会触发子组件的样式更新


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

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