Vue3 - 表没有响应更新? axios请求

发布于 2025-01-12 00:13:21 字数 2515 浏览 0 评论 0原文

我正在尝试根据附近区域的谷歌地图查询动态更新表格。该查询在 onMounted 生命周期中返回正确的数据,但在渲染时不会返回适当的数据或显示它。

我尝试过使其成为反应式、参考、将其转移到另一种方法等等。

axois 请求实际上正在记录相关数据,正如我在下面的程序中标记的那样,但在渲染时实际上并没有返回 axios get 值。

  <script>
    import { reactive, ref, onMounted } from "vue";
    import Vue3Geolocation from "vue3-geolocation";
    const axios = require("axios");
    export default {
      name: "App",
      setup() {
        let fjson = ref(null);
    
        onMounted(async () => {
          const URL = google query url
          fjson.value = await axios.get(URL, {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
            },
          });
    
          fjson.value = JSON.parse(JSON.stringify(fjson.value));
    
          **** THIS LOGS THE RIGHT VALUE! ****
          console.log(fjson.value.data.results);
    
          if (fjson.value.data.results.length > 2) {
            for (let index = 0; index < 3; index++) {
              console.log(fjson.value.data.results[index]);
            }
          }
    
          **** ALSO WORKS! ****
          fjson.value.data.results.forEach((place) => {
            const lat = place.geometry.location.lat;
            const lng = place.geometry.location.lng;
            let marker = new google.maps.Marker({
              position: new google.maps.LatLng(lat, lng),
              map: map,
            });
    
            google.maps.event.addListener(marker, "click", () => {
              infowindow.setContent(
                `<div class="ui header">${place.name}</div><p>${place.vicinity}</p>`
              );
              infowindow.open(map, marker);
            });
          });
        });
    
        **** LOGS NULL :( ****
        console.log(fjson.value);
        return { mapDiv, coords, fjson: fjson.value };
      },
    };
    </script>
    
    <template>
      <div class="row">
        <div class="col-lg-8 col-md-8 col-sm-12 d-flex align-items-stretch">
          <div class="card" style="width: 100%">
            <div class="card-header text-white" style="background-color: #00aa9e">
              <div v-for="result in fjson">
                <p>{{ result }}</p>
              </div>
              Nearby churches
            </div>
          </div>
        </div>
      </div>
    
      <div ref="mapDiv" style="width: 100%; height: 80vh" />
    </template>

I am trying to dynamically update a table based on a google maps query of nearby areas. The query is returning the right data in the onMounted lifecycle, but does not return the appropriate data or display it when it comes time to render.

I have tried making it reactive, a ref, moving it to another method and much more.

The axois request actually is logging the relevant data, as I mark in the program below, but does not actually return the axios get value when rendering.

  <script>
    import { reactive, ref, onMounted } from "vue";
    import Vue3Geolocation from "vue3-geolocation";
    const axios = require("axios");
    export default {
      name: "App",
      setup() {
        let fjson = ref(null);
    
        onMounted(async () => {
          const URL = google query url
          fjson.value = await axios.get(URL, {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
            },
          });
    
          fjson.value = JSON.parse(JSON.stringify(fjson.value));
    
          **** THIS LOGS THE RIGHT VALUE! ****
          console.log(fjson.value.data.results);
    
          if (fjson.value.data.results.length > 2) {
            for (let index = 0; index < 3; index++) {
              console.log(fjson.value.data.results[index]);
            }
          }
    
          **** ALSO WORKS! ****
          fjson.value.data.results.forEach((place) => {
            const lat = place.geometry.location.lat;
            const lng = place.geometry.location.lng;
            let marker = new google.maps.Marker({
              position: new google.maps.LatLng(lat, lng),
              map: map,
            });
    
            google.maps.event.addListener(marker, "click", () => {
              infowindow.setContent(
                `<div class="ui header">${place.name}</div><p>${place.vicinity}</p>`
              );
              infowindow.open(map, marker);
            });
          });
        });
    
        **** LOGS NULL :( ****
        console.log(fjson.value);
        return { mapDiv, coords, fjson: fjson.value };
      },
    };
    </script>
    
    <template>
      <div class="row">
        <div class="col-lg-8 col-md-8 col-sm-12 d-flex align-items-stretch">
          <div class="card" style="width: 100%">
            <div class="card-header text-white" style="background-color: #00aa9e">
              <div v-for="result in fjson">
                <p>{{ result }}</p>
              </div>
              Nearby churches
            </div>
          </div>
        </div>
      </div>
    
      <div ref="mapDiv" style="width: 100%; height: 80vh" />
    </template>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时间海 2025-01-19 00:13:21

onMounted()setup() 方法期间不会被调用,这只是在安装组件时设置回调。 setup() 方法将在调用 onMounted() 回调之前运行并完成。由于 console.log(fjson.value); 位于 setup() 方法的末尾,因此它会在 onMounted() 中的任何代码之前调用code> 被执行,所以它会是 null,这不是一个错误。本质上,流程如下所示:

  1. setup() 被调用
  2. fjson 被初始化
  3. onMounted 回调被设置
  4. 日志 fjson
  5. setup() 完成
  6. 调用 onMounted 并设置 fjson

看起来您还有另外两个问题。

您的返回语句应该是:

return { mapDiv, coords, fjson };

您要确保返回反应对象。如果您只返回 value,您将在返回时获得值,该值将为 null,并且不会由 onMounted 回调更新。

您的 v-for 应该是:

<div v-for="result in fjson.value.data.results">
   <p>{{ result }}</p>
</div>

您希望确保告诉 Vue 用于 v-for 的正确属性,就像您为 所做的那样forEach

onMounted() isn't called during the setup() method, this is just setting up a callback for when the component is mounted. The setup() method will run and complete before the onMounted() callback is called. Since console.log(fjson.value); is at the end of the setup() method it's called before any of the code in onMounted() is executed, so it will be null there, that is not a bug. Essentially the flow would look like:

  1. setup() is called
  2. fjson is initialized
  3. The onMounted callback is setup
  4. Log fjson
  5. setup() finishes
  6. onMounted is called and fjson is set

It looks like you have two other issues.

Your return statement should be:

return { mapDiv, coords, fjson };

You want to make sure you're returning the reactive object. If you just return value you'll get the value at the time of the return, which would be null and won't be updated by the onMounted callback.

Your v-for it should be:

<div v-for="result in fjson.value.data.results">
   <p>{{ result }}</p>
</div>

You want to make sure you're telling Vue the correct property to use for the v-for same as you would for forEach.

流星番茄 2025-01-19 00:13:21

onMounted 在 setup 函数之后调用。由于您的 console.log(fjson.value);在 onMounted 回调之外,它在 axios 请求之前运行。

你的 v-for 也是错误的。应该是:

<div v-for="result in fjson.data.results">
    <p>{{ result }}</p>
</div>

因为 results 是实际的数组

onMounted is called after the setup function. Since your console.log(fjson.value); is outside of your onMounted callback, it runs before your axios request.

your v-for is also wrong. It should be:

<div v-for="result in fjson.data.results">
    <p>{{ result }}</p>
</div>

since results is the actual array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文