可重用的Vue.js Ajax方法。将Vue数据数组名称作为参数传递。怎么样?

时间:2019-08-25 06:39:45

标签: javascript jquery vue.js

过去9个小时我已经学习了一些Vue.js

以下代码是我尝试将Vue.js与JQuery Ajax结合使用的情况。

我在尝试找出如何使最后一个论点发挥作用时遇到了挑战。看来,如果我传递了预期在vue data: {...中已经存在的数组的名称,则什么也不会发生。它只是空的。

更新:我已更正了COORS问题。控制台日志正常工作。

这是 json文件结构

{
  "status": "DB_SUCCESS",
  "users":[
    {
      "id":"1",
      "name":"John",
      "email":"johnk@yopemail.com",
      "phone":"121323232"
    },
    {
      "id":"2",
      "name":"Kelly",
      "email":"kellyk@yopemail.com",
      "phone":"121212122"
    },
    {
      "id":"3",
      "name":"Ryan",
      "email":"ryank@yopemail.com",
      "phone":"22222212"
    }
  ]
}

代码:

<html>
  <head>
    <!-- META TAGS -->
    <meta charset="utf-8">
    <!-- BOOTSTRAP CSS v4.3.1 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <!-- GOOGLE FONT CSS - Roboto Mono -->
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:100,300,400,500,700&display=swap" rel="stylesheet">
    <!-- GOOGLE FONT CSS - Material Icons -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- FLATPICKR CSS v4 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <!-- JQUERY    JS v3.4.1 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- VUE JS v2.6 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- <script src="vue.js"></script> -->
  </head>
  <body>
    <!-- PARENT CONTAINER -->
    <div class="container bg-light" id="app" style="min-height: 400px;">
      <!-- FORM -->
      <form class="bg-secondary" style="min-height: 350px;">
        <!-- HEADING -->
        <h2 v-if="titleVisible == true">{{ title }}</h2>
        <!-- FORM-ROW -->
        <div class="form-row mb-3">
          <!-- ROW > COLUMN -->
          <div class="col">
            <!-- BUTTON GET USERS -->
            <button type="button" class="btn btn-dark" v-on:click="ajaxGetUsers([ {key1: 'value1', key2: 'value2'} ], 'https://api.myjson.com/bins/10hzkz')">Get Users</button>
          </div>
        </div>
        <!-- FORM-ROW -->
        <div class="form-row">
          <!-- ROW > COLUMN -->
          <div class="col">
            <!-- LIST-GROUP -->
            <ul class="list-group">
              <!-- LIST-GROUP-ITEM -->
              <li class="list-group-item" v-for="user in arrUsers"> Id: {{ user.id }} - Name: {{ user.name }} - Email: {{ user.email }} - Phone: {{ user.phone }}</li>
            </ul>
          </div>
        </div>
      </form>
    </div>

    <script>

      // VUE APP INSTANCE
      var App = new Vue({
        el: '#app',
        data: {
          title: 'App 1.0',
          titleVisible: true,
          arrUsers: [] // initialize empty array
        },

        methods: {


          ajaxGetUsers: function ( jsDataArray  = null, jsonEndPoint = null) {
            
            // VALIDATE ARGS
            if(Array.isArray(jsDataArray) === false || jsonEndPoint === null) {
              // DEBUG
              console.error("(i) - AJAX FUNCTION PARAMETERS INCORRECT.");

              return false;
            };

            // CREATE A CLOSURE TO ACCESS COMPONENT IN AJAX "DONE" CALLBACK BELOW
            var self = this;

            // SERIALIZE ARRAY OF OBJECTS
            // let jsDataArray = $("#form1").serializeArray();

            // CUSTOM ARRAY OF OBJECTS
            // let jsDataArray = [
            //   {
            //     key1: 'value1',
            //     key2: 'value2',
            //   }
            // ];

            // DEBUG
            console.info("(i) - JS ARRAY   : POST DATA: ", jsDataArray);
            // JSON.STRINGIFY
            let jsonDataArray = JSON.stringify(jsDataArray);
            // DEBUG
            console.info("(i) - JSON ARRAY : POST DATA: ", jsonDataArray);

            // DEBUG
            console.warn("AJAX request started.");

            // AJAX REQUEST (SELECT - SINGLE RECORD)
            $.ajax(

              {
                url:         jsonEndPoint,
                method:      "GET",
                contentType: "application/json; charset=utf-8",
                dataType:    "text",
                data:        jsonDataArray,
                timeout:     5000,
              }

              //  (!) - AJAX EVENT: BEFORE-SEND
            ).then(function (data) {

                // DO Something...

                // DEBUG
                console.info("(x) - AJAX EVENT : BEFORE-SEND finished.");

                // RETURN data
                return data;
              }

              //  (!) - AJAX EVENT: DONE
            ).done(function (data, textStatus, jqXHR) {

                // VALIDATE data
                if (data != null) {

                  // JSON.PARSE API END-POINT RESPONSE DATA
                  let jsObject = JSON.parse(data);

                  // DEBUG
                  // console.log("JS OBJECT: ", data);

                  // SERVER RESPONSE STATUS
                  let serverResponse = jsObject;

                  // console.log('here: ', $data.vueDestArray);
                  // *** UPDATE VUE ARRAY arrUsers ***
                  // Update a Template data object property.
                  // self.arrUsers = serverResponse[jsonTargetNode];
                  
                  self.arrUsers = serverResponse.users;

                  // WE USE serverResponse[jsonTargetNode] INSTEAD OF serverResponse.jsonTargetNode 
                  // BECAUSE jsonTargetNode IS AN ARGUMENT VARIABLE OF OUR ajaxGetUsers METHOD.
                  // IT CANNOT BE ACCESSED VIA DOT NOTATION.

                  // DEBUG
                  // console.info("(x) - AJAX EVENT :        DONE finished.", serverResponse[jsonTargetNode]);
                  
                  // DEBUG
                  console.info("(x) - AJAX EVENT :        DONE finished.", serverResponse.users);

                  // MYSQL - CONNECTION SUCCESS
                  if (serverResponse.status == "DB_SUCCESS") {
                    // DEBUG
                    console.info(" |->  SERVER RESPONSE: ", serverResponse.status);
                  }

                  // MYSQL - CONNECTION ERROR
                  if (serverResponse.status == "DB_ERROR") {
                    // DEBUG
                    console.error(" |->  SERVER RESPONSE: ", serverResponse.status);
                  }

                  // [additional serverResponse conditions go here...]

                }

              }

              // AJAX FAIL
            ).fail(function (jqXHR, textStatus, errorThrown) {
                // DEBUG
                console.error("(x) - AJAX EVENT : FAIL fired.", errorThrown);
              }

              // AJAX ALWAYS
            ).always(function () {
              // DEBUG
              console.info("(x) - AJAX EVENT :      ALWAYS finished.");
              // DEBUG
              console.warn("AJAX request finished.");
            });

          } // end ajaxGetUsers : function

        }, // end vue methods

        beforeCreate: function() {
          // 1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
          
          // DO Something...
          this.title = 'Loading app... beforeCreate';
          console.info('Loading app... beforeCreate');

        },

        created: function() {
          // 2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which
          // means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting 
          // phase has not been started, and the $el property will not be available yet.
          
          // DO Something...
          this.title = 'Loading app... created';
          console.info('Loading app... created');

          this.ajaxGetUsers([ {key1: 'value1', key2: 'value2'} ], 'https://api.myjson.com/bins/10hzkz');

        },

        beforeMount: function() {
          // 3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
          
          // DO Something...
          this.title = 'Loading app... beforeMount';
          console.info('Loading app... beforeMount');

        },

        mounted: function() {
          // 4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
          
          // DO Something...
          this.title = 'Loading app... mounted';
          console.info('Loading app... mounted');

          // this.ajaxGetUsers([ {key1: 'value1', key2: 'value2'} ], './jsonEndPoint.php');

        },

        beforeUpdate: function() {
          // 5. beforeUpdate: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
          
          // DO Something...
          this.title = 'Loading app... beforeUpdate';
          console.info('Loading app... beforeUpdate');

        },

        updated: function() {
          // 6. updated: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
          
          // DO Something...
          // this.title = 'Loading app...updated';

        }

      }); // end Vue APP
      
    </script>  
    <!-- JQUERY    JS v3.4.1 -->
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> -->
    <!-- POPPER    JS v1.14.7 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <!-- BOOTSTRAP JS v4.3.1 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

可能必须将数据声明为函数,但如果没有看到实际的最终代码,则很难预测。

请在这里查看:

https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

此外,为了使您的AJAX函数可重复使用,您可以在注释中要求将回调函数传递给您的“ ajaxGetUsers()”,然后在AJAX请求的“ done()”方法中调用它。

这样,您可以在回调函数中处理结果,从而使AJAX函数可重用。