我的商店和状态正在正确更新。我正在使用
Ionic
与 vue.js
与 Pinia 组合。
当我在上一条路线上进行选择以选择新图像时,图像会在
pinia
中正确更新,但图像在下一条路线中不会反应。即使 pinia 已更新,它也会以未定义的形式返回,我只是得到一张空白图像。图像路径是正确的,我只是无法反应。
如何使用
vue.js
合成获得对商店中更改的图像的反应性?
else 语句为 true console.warn('图像数据未定义或缺少名称。');
代码
<template>
<ion-page>
<mm-header pageTitle="Select Color">
<template v-slot:select-button>
<a href="#" @click.prevent="selectAndSave">Select</a>
</template>
</mm-header>
<ion-content :fullscreen="true">
<div :class="`bg-${themeColor}-500 h-full`">
<img :src="mmImage" alt="Image" v-if="mmImage" class="w-full" />
</div>
</ion-content>
</ion-page>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { ref, computed } from 'vue';
import { onIonViewDidEnter } from '@ionic/vue';
import { useMantraStore } from '@/stores/MantraStore';
import { IonPage, IonContent } from '@ionic/vue';
const router = useRouter();
const mantraStore = useMantraStore();
const themeColor = computed(() => mantraStore.myMantra.color);
const mmImage = ref('');
onIonViewDidEnter(() => {
console.log('Home page did enter');
if (mantraStore.myMantra.image && mantraStore.myMantra.image.name) {
console.log('Image name:', mantraStore.myMantra.image.name);
mmImage.value = new URL(`/src/assets/images/mantra-images/portrait/${mantraStore.myMantra.image.name}`, import.meta.url).href;
console.log('Image path:', mmImage.value);
} else {
console.warn('Image data is undefined or missing name.');
}
});
const selectAndSave = () => {
router.push('/select/photo');
};
</script>
数据
state: () => ({
myImage: {
color:'yellow',
image:{
id:0,
name:'0-1440x3200.gif',
alt:'Happy faces'
}
}
}),
反应性意味着当依赖关系发生变化时重新计算值。
您只需在
mmValue
中设置 onIonViewDidEnter
,且仅被调用一次。因此,当 onIonViewDidEnter
被触发时,ref 值不会改变。
这会起作用:
import { computed } from 'vue'
const mmImage = computed(() => {
if (mantraStore.myMantra.image && mantraStore.myMantra.image.name) {
console.log('Image name:', mantraStore.myMantra.image.name);
const result = new URL(`/src/assets/images/mantra-images/portrait/${mantraStore.myMantra.image.name}`, import.meta.url).href;
console.log('Image path:', result);
return result
} else {
console.warn('Image data is undefined or missing name.');
}
})
computed
将执行该函数并收集依赖项,然后在依赖项发生变化时重新执行该函数。