【问题标题】:Get Data From PHP And Display In Vue From Fetch从 PHP 中获取数据并从 Fetch 中显示在 Vue 中
【发布时间】:2021-06-30 21:12:07
【问题描述】:

我正在尝试学习 Vue.js。我正在构建一个非常小的组件。该组件实际上只是一个使用 select 的选项列表。在文档或我可以在网上找到的任何教程中,都没有显示如何将数据从数据库加载到 Vue 组件中。我找到了一些使用 Axios 的示例,但我对使用 Axios 完全没有兴趣。我只是想了解 Vue 是如何工作的,这样我就可以看看是否可以使用它来改进我的工作流程。这实际上是一个基本的测试用例。此外,此代码引用的 PHP 部分工作正常。我已经直接测试过了,它加载的数据完全符合预期。

这里是javascript部分。

const cityChoice = {
    data() {
        return {
            citys: [
                { Abbrev: 'Lima' },
                { Abbrev: 'FtWayne' },
            ],
            err: false
        }
    },

    methods: {

    },
    mounted() {
        fetch('Controller/get_cities.php', {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            headers: {
                // 'Content-Type': 'application/json'
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: '' // body data type must match "Content-Type" header
        }).then(function (response) {
            return response.text();
        }).then(function (data) {
            testData = data
            return testData;
        });

    },

    methods: {
        getCities() {
            fetch('Controller/get_cities.php', {
                method: 'POST', // *GET, POST, PUT, DELETE, etc.
                cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                headers: {
                    // 'Content-Type': 'application/json'
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                redirect: 'follow', // manual, *follow, error
                referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
                body: '' // body data type must match "Content-Type" header
            }).then(function (response) {
                return response.text();
            }).then(function (data) {
                this.citys = data;
                alert(this.citys)
            });
            this.citys = [
                { Abbrev: 'Dayton' },
                { Abbrev: 'Cincy' },
            ]

        }
    }
}

Vue.createApp(cityChoice).mount('#cityChoice')

这里是 HTML 部分。

<?php
$lifetime = 60 * 60 * 24 * 14;
session_set_cookie_params($lifetime, '/');
session_start();
include 'Controller/login_check.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/vue@next"></script>
    <title>BAI Inventory Entry</title>
</head>
<body>
    <div id="cityChoice">
        <select id="city">
            <option v-for="city in citys">
                {{ city.Abbrev }}
            </option>
            </select>
            <button v-on:click="getCities">Get Cities</button>
    </div>
    
</body>
<script src="js/global.js?ver3"></script>
</html>

我很肯定我只是不了解这种软件语言的工作原理。但是,我需要了解它是如何调用真实数据的,否则我将永远无法围绕它的其他基础知识进行思考,因为我经常发现自己在问“为什么这比仅仅编码更好” javascript”。我正在尝试了解如何使这个简单的示例发挥作用,以便我能够克服脑海中的那个问题并继续学习这门语言。

我已经尝试过使用“mounted”和“created”来加载 getCities 方法,同时将城市的数据部分设置为“”。还是没有骰子。当使用数组和/或 JSON 数据对城市进行硬编码时,它会完全按预期加载。

更新:我已将代码调整为现在在 javascript 部分中显示的内容。使用 chrome 工具,我可以看到我的城市变量充满了 JSON 对象数组,但我仍然没有将任何数据放入 Select 列表中。我完全不知道为什么这不起作用,以及为什么这似乎很难做到。而且...这实际上只是将几个城市加载到下拉列表中的代码。

更新 2:显然 Vue 不允许从 Fetch 内部更新项目。我已经更新了代码以显示我的测试。我的 API 可以正常返回数据,并且我已经多次验证。我已经尝试在最终的 fetch .then 部分中对 this.citys 进行硬编码,但它不起作用。但是,当我在 fetch 之外对其进行硬编码时(如上面的代码所示),它可以正常工作。我到了不得不假设这是 Vue 的限制的地步,这对我来说似乎很疯狂。我在 Stackoverflow 上发现了另一个有同样问题的问题,但答案实际上只是告诉他完全按照我上面一直在尝试做的事情去做。而且,我无法评论询问他是否找到了解决方案,因为我没有足够的声誉。

【问题讨论】:

  • 我认为你只需要在fetch之前添加一个回报
  • 你缺少一个结尾 &lt;/select&gt; 标签
  • 我之前的回答不正确,我没有意识到您正在尝试将其添加到页面中。但是如果您从头开始并想使用 php 作为您的 api nuxt 是一个不错的解决方案
  • 我对使用 nuxt 不感兴趣。我只是想提高我的技能,这样我就可以改进我的简历。我维护了几个用 vanilla JS 构建的复杂文件,但每次我尝试选择其中一个框架时,我都会感到沮丧,因为没有任何文档或教程提供有关如何使用真实数据库和 PHP 后端的任何信息。我在认真地质疑为什么像 Vue 和 React 这样的东西被如此推崇。上面的代码需要我 15 到 20 行 javascript 代码才能完全完成。

标签: php vue.js


【解决方案1】:
//Html
<div id="cityChoice">
    /* <select > to load options on mounted use mounted hook*/
    /* <select v-on:click="getCities">  to load options on click(whatever event)*/
      <option v-for="city in cities">
          {{ city.City }}
      </option>
    </select>
</div>

var app3 = new Vue({
  el: '#cityChoice',
  data(){
    return {
      cities:[],
      err:false
    }
  },
  methods:{
      async getCities() {
        //fetch -> assumption: the php call works -> u can use postman to test this
        let data = await fetch('Controller/get_cities.php', {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
      })



      //Data will likely have a data.data field
      if( data in data && !data.error){
        //Set data
        this.cities = data.data //this assumes that data.data is correctly formatted from ur php call
      }else{
        this.err = true
      }
      }
  },
  //Add if you want data loaded on paint
  created(){
 // or mounted(){
    this.getCities()
  }
})

查看 hello world 示例 https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-hello-world

【讨论】:

  • 没有。上面代码示例中的任何内容都没有为我提供更新现有代码以使其正常运行的信息。您链接到的 hello world 示例不使用数组,因此与我正在处理的用例不匹配。
  • 我怀疑fetch 库配置不正确。查看您的 API 路由,它仅包含对 Controller/get_cities.php 的本地引用。这应该是一个 URL 地址(主机地址/域通常是设置 fetch 的一个选项,但不是必需的)。 1) 首先,我将使用postman 确定您的 API 调用是否有效以及在哪个地址。如果它不起作用,为什么??? postman 有很多选项,可以使用 cookie 等处理请求。(app.getpostman.com/app/download) 2) 查看 fetch api 文档并在 3) 中进行设置。控制台记录 fetch 的结果
  • 我还想指出,您的问题涉及组件,但您的代码未设置为组件vue.component('name',{ /*options*/})vuejs.org/v2/guide/components-registration.html
  • 过去三个小时我一直在研究这个问题。我的 fetch 库工作正常。 api返回数据很好。当我在代码中添加“alert(this.cities)”时,它会给我一个警报,其中 JSON 数据完全按照预期逐项列出。无论出于何种原因,Vue.js 都不允许从 fetch 调用内部更新 this.cities。我什至尝试将 fetch 代码中的 this.cities 硬编码为与我开始时完全相同的数组,但它不起作用。如果我在 fetch 之外进行同样的硬编码,它确实如此。
【解决方案2】:

在这个问题上找到了让我找到答案的信息。

Updating a vuejs alert component from a fetch return value

我将包含我更新的代码,以防有人遇到此问题而不是此处链接的问题。

我不得不将 response.text() 更新为 response.json(),但最大的问题是在 fetch 函数内部无法识别 this 的问题。我知道,但是在学习 vue 的过程中,我认为这会表现得不同。

const cityChoice = {
    data() {
        return {
            citys: [
                { Abbrev: 'Lima' },
                { Abbrev: 'FtWayne' },
            ],
            err: false
        }
    },

    methods: {

    },
    mounted() {
        var self = this;
        fetch('Controller/get_cities.php', {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            headers: {
                // 'Content-Type': 'application/json'
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: '' // body data type must match "Content-Type" header
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            self.citys = data;
        });

    },

    methods: {
        getCities() {
            var self = this;
            fetch('Controller/get_cities.php', {
                method: 'POST', // *GET, POST, PUT, DELETE, etc.
                cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                headers: {
                    // 'Content-Type': 'application/json'
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                redirect: 'follow', // manual, *follow, error
                referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
                body: '' // body data type must match "Content-Type" header
            }).then(function (response) {
                return response.json();
            }).then(function (data) {
                self.citys = data
            });


        }
    }
}

Vue.createApp(cityChoice).mount('#cityChoice')

希望这对尝试学习新语言的其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2020-05-08
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2019-04-12
    相关资源
    最近更新 更多