Firstly, I know this is probably a SUPER easy question, but I've been struggling for an hour and half and I'm kinda done with that. First vue project ever, so I've never had 2 components talk to each other, let alone when <script setup>
is involved.
Any relevant docs that help me understand WHY this works this way would be wonderful. I want to learn how this works, but my google searching is getting me nowhere.
This app is simple, its just toggling light mode and dark mode on some cards. There's more to it than what's below, but I've stripped away the irrelevant (working) code for ease of reading.
My App.vue code:
<script setup>
import {ref, defineProps} from "vue";
import card from './components/card.vue'
const darkMode = ref(false);
const props = defineProps({
darkMode: Boolean
})
</script>
<template>
// Bunch of stuff that is irrelevant to the scope of this problem, it works just fine.
</template>
My card.vue code:
<script xmlns="http://www.w3.org/1999/html">
export default {
data() {
return {
}
},
}
</script>
<template>
<h1 :class="{ 'text-white': darkMode }"> Content! </h1>
</template>
There's more complexity to the project, but all I'm trying to do right now is get them to talk. I just want the class to be added based on whether darkMode
is true
or false
in the parent.
To enable the card.vue
component to receive darkMode
, it needs to have a prop (via defineProps
in <script setup>
or the props
option in <script>
). However, you've declared the darkMode
prop in App.vue
when it actually needs to be in card.vue
. Also note there's no need to import defineProps
, as it's a compiler macro that automatically gets replaced by the compiler:
<!-- App.vue -->
<script setup>
import { ref } from 'vue'
import card from './components/card.vue'
const darkMode = ref(false);
// ❌ move this to card.vue
//const props = defineProps({
// darkMode: Boolean
//})
</script>
<!-- card.vue -->
<script setup>
// ✅ card.vue can now receive `darkMode` from parent
const props = defineProps({
darkMode: Boolean
})
</script>
Then, use the v-bind
directive to bind the value of App.vue
's darkMode
ref to card.vue
's darkMode
prop:
<!-- App.vue -->
<template>
<card :darkMode="darkMode" />
</template>