[Vuejs]-How could I change an image in a child page when pressing a button in its parent page?

1👍

Below is a simple example

Vue.component('About', {
 name: 'About',
 template: `<div>
   <div v-if="mode==='dark'">Dark</div>
   <div v-else>Light</div>
  </div>
 `,
 data() {
  return {
   mode: 'light',
  };
 },
 mounted() {
  this.setMode('white'); // In realtime use `this.getMode()` instead of 'white'
 },
 methods: {
   setMode(val) {
     this.mode = val;
   },
   getMode() {
     return JSON.parse(localStorage.getItem('mode'));
   }
 }
});

var app = new Vue({
 el: "#app",
 template: `<div>
   <input type="checkbox" v-model="toggler" @input="setVal" />
   <About ref="about" />
 </div>`,
 data() {
  return {
    toggler: false,
  };
 },
 methods: {
   setVal() {
    const mode = this.toggler === false ? 'dark' : 'light';
    // localStorage.setItem('mode', mode); // In realtime uncomment this line
    this.$refs.about.setMode(mode);
   }
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>

2👍

Yes, the local storage is for keeping data not propagate events.
The simplest way for you is to make a prop in child component and pass the value by this prop. But if you want to implement it as global variable the suggested way is by Pinia.

Leave a comment