我在父组件中有一个子组件。每当单击子组件时,我都需要应用一个调用.selected
它的类。
父级.vue
<template>
<ol>
<li v-for="(Contact, index) in Contacts">
<Component-Contact :ref="(el) => { RefContacts[index] = el}" @click="onClick(RefContacts[index])" :Contact="Contact" @Selected="(Data) => onSelected(Data)"/>
</li>
</ol>
</template>
<script>
import ComponentContact from '../components/Contact.vue'
....
setup() {
const RefContacts = ref([]);
function onSelected(Contact){
//Adds data received from child component to an array
}
onClick(el) {
el.toggleClass('selected') // Returns error saying toggleClass is not a function!!
}
const Contacts = ref();
onMounted(() => {
const Result = await axios.get(`/api/contacts`);
Contacts.value = Result.data
}
)
return {
Contacts, // An array of contacts from the DB
onSelected
}
}
</script>
子组件 Contact.vue
<template>
<div style="cursor: pointer" @click="onClick($el, Contact)">
<p>{{Contact.Forename}}</p>
<p>{{Contact.Surname}}</p>
</div>
</template>
<script>
...
props: {
Contact: {
type: Object,
required: true
},
emits: 'Selected',
setup() {
function onClick(el, Contact) {
el.toggleClass('selected') // This works but I don't want to set it here in the child
return context.emit('Selected', {
FullName: Contact.forename + ' ' + Contact.surname
}
}
}
</script>
我如何让 Vue 将类应用于.selected
视图<Child-Component />
中Parent.vue
?我想在父级中设置它(或使用它的任何其他地方),然后在用户完成操作时删除该类。我觉得这比在子组件中设置它更灵活。
尽可能避免 DOM 操作。
不要自己应用类,而是让 Vue 来做:
请参阅类和样式绑定。
基本示例,其中只能选择一个项目(选择另一个项目将取消选择前一个项目):
这里你可以单独选择项目:
在每种情况下,我都会保留最小的本地状态(在父级中)。当状态被修改时,Vue 会更新模板。