首页 > 解决方案 > Vue 3组合Api:V-For循环不访问数据

问题描述

我有这个模板

我的问题是location.drawnfeatures模板由于某种原因没有更新我可以看到我有正确的数据console.log并且我没有测试过'v-for'并且代码有效

如果我把v-if="location.drawnFeatures.length"我得到错误说长度没有定义..

我试着.value到处添加

为什么 vue3 不访问数据?

<ol-feature v-for="(feature, index) in location.drawnfeatures" :key="'feature'+uid+index">
  <ol-geom-point :coordinates="feature.coordinates"></ol-geom-point>

位置定义如下:

props:{
 locationData:Object,
},
setup(props){
  const location = ref({
    center:[0, 0],
    zoom:5,
    coordinates:null,
    rotation: 0,
    name:null,
    title:null,
  })

 onMounted(() => {
  location.value = props.locationData && props.locationData.location ? props.locationData.location : location.value
  console.log(location.value)
 });
}

我也尝试过在setup()

const locationData = toRef(props)

如果我这样做,console.log(locationData.value)我会不确定

但这也不起作用

标签: vue.jsvuejs3

解决方案


如果你解构通过 props 获得的对象,解构后的值将失去反应性:

但是,因为 props 是反应性的,所以不能使用 ES6 解构,因为它会移除 props 的反应性。

似乎location.value = props.locationData.location您正在从道具访问嵌套对象值,并且它不保持反应性。

根据代码,看起来应该可以locationData直接在 for 循环中使用该道具:

<ol-feature v-for="(feature, index) in locationData.location.drawnfeatures" :key="'feature'+uid+index">

您还可以在道具中设置默认对象,您可能不需要在设置中定义位置。

props: {
 locationData: {
  type: Object,
  default() {
   return {
    location: {
     center: [0, 0],
     zoom: 5,
     coordinates: null,
     rotation: 0,
     name: null,
     title: null,
    }
   }
  }
 }
}

推荐阅读