从零打造简单状态管理
状态管理
如果你有一处需要被多个实例间共享的状态,你可以使用一个 reactive 方法让对象作为响应式对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>状态管理</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app-a">App A: {{ message }}</div>
<div id="app-b">App B: {{ message }}</div>
<script>
const {createApp,reactive} =Vue
const sourceOfTruth=reactive({
message:"Hello"
})
const appA=createApp({
data(){
return sourceOfTruth
},
}).mount("#app-a")
const appB=createApp({
data(){
return sourceOfTruth
},
mounted(){
sourceOfTruth.message='GoodBye'
}
}).mount("#app-b")
</script>
</body>
</html>
如何能更好的解决这个问题可以引入store模式,状态都放置在 store 自身的 action 中去管理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>引入store</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app-a">{{sharedState.message}}</div>
<div id="app-b">{{sharedState.message}}
<button @click="clearState"></button>
</div>
<script>
const {createApp,reactive} =Vue
const store = {
debug: true,
state: reactive({
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 = ''
}
}
const appA = createApp({
data() {
return {
privateState: {},
sharedState: store.state
}
},
mounted() {
store.setMessageAction('Goodbye!')
}
}).mount('#app-a')
const appB = createApp({
data() {
return {
privateState: {},
sharedState: store.state
}
},
methods:{
clearState(){
console.log("准备清除数据");
store.clearMessageAction()
console.log("打印清清除后的结果",store.state.message);
store.setMessageAction("这是测试数据")
console.log("设置了新值",store.state.message);
}
}
}).mount('#app-b')
</script>
</body>
</html>