我正在使用选项 API 和 pinia 将应用程序从 Vue2 转换为 Vue3。这不像我想要的那样工作......
<template>
<div>
<pre>My Point: {{ myPoint(long, lat) }}</pre>
<pre>ActiveEvent: {{ [ActiveEvent.long, ActiveEvent.lat] }}</pre>
</div>
</template>
<script setup>
import { ref, computed, reactive, defineProps, onMounted, onBeforeUpdate, onBeforeMount } from 'vue'
import { useStore } from '../stores/store.js'
//import * as turf from '@turf/turf'
//const props = defineProps(['ActiveEvent'])
let store = useStore()
let ActiveEvent = computed(() => store.ActiveEvent)
var lat = ref(ActiveEvent.lat)
var long = ref(ActiveEvent.long)
const myPoint = function (lat, long) {
return [long, lat]
}
</script>
它给我以下结果:
My Point: [
null,
null
]
ActiveEvent: [
-2.78309353537633,
52.7076467374228
]
ActiveEvent 的插值作用于存储负载的反应性,但函数在加载数据之前触发(我假设),这就是我得到空响应的原因。如果我明确设置
如何在数据可用时推迟(或重新呈现)My Point 的值。
如果我将 ActiveEvent 作为道具传递并在 onBeforeMounted() 挂钩中设置变量值,我可以让它工作,但我宁愿从商店获取它们。
这应该有效1:
import { useStore } from '../stores/store.js'
import { storeToRefs } from 'pinia'
const { ActiveEvent } = storeToRefs(useStore())
const myPoint = computed(() => {
const { long, lat } = ActiveEvent.value
return [long, lat].some((val) => typeof val !== 'number') ? null : [long, lat]
})
模板:
<template>
<!-- ... -->
<template v-if="myPoint">
<!--
you can safely do stuff with myPoint here, both its
long and lat are numbers
-->
...
</template>
</template>
如果有任何不清楚的地方,请告诉我,我会详细说明。
如果您在多个地方需要它,请在商店中创建一个吸气剂返回
ActivePoint
作为null
或ActiveEvent
的long
和lat
的消毒(类型检查)阵列,所以你不必在使用它的每个组件中进行检查。
检查应该只在模板级别,如果
ActivePoint
是否真实。
另一个优点是你不关心存储中的
.value
,因为状态是一个反应对象。
1 - 如果
long
或lat
永远是NaN
,检查应该是:
(val) => typeof val !== 'number' || !isFinite(val)
如果你只想防御
null
s,你可以使用
(val) => val === null