I can't find a way to pass data from a component to a non child component in vue. I'm working with a blade file and I have a component to toggle between darkmode and lightmode. I want my dark logo to show if dark and light logo to show if light. The problem is provide/inject can't solve the issue I see in Vue dev tool that my value is provided but when i check the other component the injected value is undefined. I did it before in a dropdown component and i was able to pass the value because It was about one parent component and its child but now I can't do it.
I need a way to pass data from my Switchdark.vue component to Svglogodark.vue component.
My Switchdark.vue
<template>
<div
@click="modeToggle"
>
<div
:
>
<div
:
></div>
</div>
</div>
</template>
<script>
import { provide, ref } from "vue";
import Svglogodark from "./Svglogodark.vue";
export default {
components: [Svglogodark],
props: ["theme"],
data() {
return {
toggleActive: false,
};
},
mounted() {
if (this.theme === "false") {
this.light();
} else {
this.dark();
}
},
methods: {
dark() {
document.querySelector("body").classList.add("dark");
this.toggleActive = true;
this.$emit("dark");
},
light() {
document.querySelector("body").classList.remove("dark");
this.toggleActive = false;
this.$emit("light");
},
modeToggle() {
if (
this.darkMode ||
document.querySelector("body").classList.contains("dark")
) {
this.light();
} else {
this.dark();
}
const isDarkModeOn = this.toggleActive;
createCookie("isDarkModeOn", isDarkModeOn.toString(), 60 * 60 * 24);
},
},
setup() {
const toggleActive = ref(toggleActive);
provide("toggleActive", toggleActive);
return {
toggleActive,
};
},
};
</script>
<style></style>
My Svglogodark.vue:
<template>
<svg
v-if="toggleActive"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="170"
height="70"
viewBox="0 0 4792 1625"
>
</svg>
</template>
<script>
export default {
inject: ["toggleActive"],
created() {
console.log(this.toggleActive);
},
};
</script>
<style></style>
I will have two SVG and i want them to show if I'm in dark mode or not.
CodePudding user response:
Use vuex here you can learn about it. vuex-docs
Or
You can use simple way that is LocalStorage
\\store item
localStorage.setItem('theme', 'dark');
\\you can get anywhere
var theme = localStorage.getItem('theme');
console.log(theme); //'dark'