我正在使用Vue-Native构建一个具有多个屏幕的简单应用程序(使用Vue Native Router)。我有这样一种情况,我在屏幕A中连接到一个监听消息的WebSocket,我需要这些更新在屏幕A和屏幕B中可用。
因此,在我对全局变量和原型属性一无所知后,我遇到了Vuex,它似乎正好做了我需要的事情。
事实上,它可以很好地更新屏幕上的属性,但它似乎不是反应性的,也不会更新屏幕。
store.js:
import Vue from "vue-native-core";
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state: {
imageUri: ["", "", "", ""]
},
mutations: {
updateImage (state, data) {
state.imageUri[data.index] = data.url;
}
}
});脚本标记中的ScreenA.vue:
import store from "./store.js"
export default {
[...]
methods: {
[...]
handleMessage: function(message){
var data = message.data.split("#", 2);
var value = data[1];
console.log("New msg");
if(data[0] == "init"){
this.connectionMs = Date.now()-value;
this.connectionStatus = 2;
}else if(data[0] == "img"){
var current = this.cImg;
this.cImg = (this.cImg+1)%4;
var dataUrl = "data:image/jpeg;base64,"+value.substring(2, value.length-1);
store.commit('updateImage', {index: current, url: dataUrl}); //<- Relevant line
}
},
[...]
}
}ScreenB.vue:
<template>
<view :style="{marginTop: 40}">
<image resizeMode="contain" :style="{ width: '100%', height: 200 }" :source="{uri: imageUri[0]}"/>
<image resizeMode="contain" :style="{ width: '100%', height: 200 , marginTop: -200}" :source="{uri: imageUri[1]}"/>
<image resizeMode="contain" :style="{ width: '100%', height: 200 , marginTop: -200}" :source="{uri: imageUri[2]}"/>
<image resizeMode="contain" :style="{ width: '100%', height: 200 , marginTop: -200}" :source="{uri: imageUri[3]}"/>
<touchable-opacity :on-press="btnPress">
<text>Press me! {{imageUri[0]}}</text>
</touchable-opacity>
</view>
</template>
<script>
import store from "./store.js"
export default {
props: {
navigation: {
type: Object
}
},
computed:{
imageUri: function(){
return store.state.imageUri;
}
},
methods: {
btnPress: function(){
console.log("ImgUrl0 -> "+this.imageUri[0]);
},
},
}
</script>只要存储中的vuex状态发生变化(console.log打印新值),计算的属性就会正确更新,但屏幕上呈现的数据(文本和图像元素)仍然是旧数据。
有没有办法解决这个问题?也许是一种完全不同的跨屏幕同步动态数据的方法?
发布于 2018-08-19 09:59:44
你的突变只会更新state.imageUri[data.index],它不会改变state.imageUri的引用。这意味着state.imageUri仍然指向旧的引用,并且Vue不能检测不到此更新。这是Vue's gotchas中的一个
一种解决方案是使用JSON.parse(JSON.stringify())制作state.imageUri阵列的深层拷贝
export default new Vuex.Store({
state: {
imageUri: ["", "", "", ""]
},
mutations: {
updateImage (state, data) {
state.imageUri[data.index] = data.url;
state.imageUri = JSON.parse(JSON.stringify(state.imageUri))
}
}
});https://stackoverflow.com/questions/51912947
复制相似问题