- 项目结构
---views
Home.vue
Son1.vue
Son2.vue
store.js
Home.vue
<template>
<div>
<Son1 />
<hr />
<Son2 />
</div>
</template>
<script>
import Son1 from "./Son1.vue";
import Son2 from "./Son2.vue";
export default {
name: "Home",
components: { Son1, Son2 }
};
</script>
Son1.vue
<template>
<div>
<button @click="send">数据同步{{ state.message }}</button>
</div>
</template>
<script>
import store from "./store.js";
export default {
data() {
return {
state: store.state
};
},
methods: {
send() {
store.setMessageAction("World");
}
}
};
</script>
Son2.vue
<template>
<div @click="send">这是来自son1的数据同步===》{{ state.message }}</div>
</template>
<script>
import store from "./store.js";
export default {
data() {
return {
state: store.state
};
},
methods: {
send() {
store.clearMessageAction();
}
}
};
</script>
store.js
let store = {
debug: true,
state: {
message: "Hello!"
},
setMessageAction(newValue) {
if (this.debug)
console.log("setMessageAction triggered with", newValue);
this.state.message = newValue;
},
clearMessageAction() {
if (this.debug) console.log("clearMessageAction triggered");
this.state.message = "";
}
};
export default store;