vue2中父子组件传参子组件页面在created中获取参数通过参数渲染样式但是当点击上一人下一人切换时样式不会跟着改变改这样改详细代码是什么
在Vue 2中,父子组件传参可以使用props进行传递。在子组件中可以通过监听props的变化来更新样式。以下是一个示例代码:
父组件:
<template>
<div>
<button @click="prevPerson">上一人</button>
<button @click="nextPerson">下一人</button>
<child-component :person="currentPerson"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
currentPersonIndex: 0,
persons: [
{ name: 'Person 1', style: 'color: red;' },
{ name: 'Person 2', style: 'color: blue;' },
{ name: 'Person 3', style: 'color: green;' }
]
};
},
computed: {
currentPerson() {
return this.persons[this.currentPersonIndex];
}
},
methods: {
prevPerson() {
this.currentPersonIndex = (this.currentPersonIndex - 1 + this.persons.length) % this.persons.length;
},
nextPerson() {
this.currentPersonIndex = (this.currentPersonIndex + 1) % this.persons.length;
}
}
};
</script>
子组件:
<template>
<div>
<h1 :style="person.style">{{ person.name }}</h1>
</div>
</template>
<script>
export default {
props: {
person: Object
},
created() {
this.updateStyle();
},
watch: {
person() {
this.updateStyle();
}
},
methods: {
updateStyle() {
// 可以在这里根据传入的person参数来更新样式
// 例如:this.person.style = 'color: red;'
}
}
};
</script>
在上述示例中,父组件通过currentPerson属性将当前的person对象传递给子组件。子组件中通过props接收person属性,并在created钩子函数中调用updateStyle方法来更新样式。同时,通过监听props的变化,在watch中也调用updateStyle方法来更新样式。这样,在切换上一人下一人时,子组件的样式会根据新的person参数重新渲染
原文地址: https://www.cveoy.top/t/topic/hXWS 著作权归作者所有。请勿转载和采集!