Vue2 父子组件传参:动态更新子组件样式,实现上一人下一人切换
在Vue2中,可以使用计算属性来根据传入的参数动态计算样式。以下是一个示例代码:\n\n父组件:\nhtml\n<template>\n <div>\n <button @click="changePerson(-1)">上一人</button>\n <button @click="changePerson(1)">下一人</button>\n <child :person="currentPerson" />\n </div>\n</template>\n\n<script>\nimport Child from './Child.vue';\n\nexport default {\n components: {\n Child\n },\n data() {\n return {\n persons: [\n { name: 'Person 1', sex: 1 },\n { name: 'Person 2', sex: 0 },\n { name: 'Person 3', sex: 1 }\n ],\n currentIndex: 0\n };\n },\n computed: {\n currentPerson() {\n return this.persons[this.currentIndex];\n }\n },\n methods: {\n changePerson(step) {\n this.currentIndex += step;\n if (this.currentIndex < 0) {\n this.currentIndex = 0;\n } else if (this.currentIndex >= this.persons.length) {\n this.currentIndex = this.persons.length - 1;\n }\n }\n }\n};\n</script>\n\n\n子组件:\nhtml\n<template>\n <div :class="personClass">{{ person.name }}</div>\n</template>\n\n<script>\n export default {\n props: {\n person: {\n type: Object,\n required: true\n }\n },\n computed: {\n personClass() {\n return this.person.sex === 1 ? 'male' : 'female';\n }\n }\n};\n</script>\n\n<style scoped>\n.male {\n color: blue;\n}\n.female {\n color: pink;\n}\n</style>\n\n\n在父组件中,我们通过currentPerson计算属性获取当前的人物对象,并将其传递给子组件。在子组件中,使用计算属性personClass根据person对象中的sex字段来动态计算样式类名。当sex为1时,添加male类名,否则添加female类名。\n\n当我们点击上一人或下一人按钮时,会改变父组件中的currentIndex值,进而改变currentPerson计算属性的值,从而触发子组件中的计算属性重新计算样式类名,实现样式的动态更新。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pG4C 著作权归作者所有。请勿转载和采集!