Asked  7 Months ago    Answers:  5   Viewed   40 times

I'm working with Laravel and Vue to make a single page web application. I've used Vue before to get the data from a database using a controller with no problem, but for some reason I'm now only getting a seemingly infinitely nested JS object that has getter and setter methods stored in each parent object instead of the data I queried. I've seen other people with similar issues, but the solutions that worked for them didn't work for me. For example, some people used JSON.parse(JSON.stringify(response.data)); to get just the raw data, but this doesn't work when I attempt to store it in this.actions. Here is my index method in my ActionLogController

public function index($url)
{

    $companyName = explode("/", $url);

    if(Auth::check())
    {
        $company = Company::where('name', '=', strtolower($companyName[count($companyName) - 1]))->first();

        // If sortby not empty
        $sortby = "created_at";

        //assume desc (most recent)
        $sortdirection = 'desc';

        if(request()->has('sortdirection') && request()->sortdirection == 'asc')
        {
            $sortdirection = 'asc';
        }

        // if sortby is set
        if(request()->has('sortby')) 
        {
            $sortby = request()->sortby;

            switch($sortby) 
            {
                case "date":
                    $sortby = "string_date";
                break;
                case "company":
                    $sortby = "company_name";
                break;
                case "name":
                    // do nothing
                break;
                case "communication-type":
                    $sortby = "communication_type";
                break;
                case "contact":
                    // do nothing
                break;
                case "subject":
                    $sortby = "status";
                break;
                case "assigned-to":
                    $sortby = "assigned_to";
                break;
                case "action":
                    $sortby = "action_item";
                break;
                case "assigned-to":
                    $sortby = "assigned_to";
                break;
                default:
                    $sortby = 'created_at';
                break;
            }
        }
    }

    if($sortdirection == 'asc') {
        return Auth::user()->actionLogs
            ->where('activity_key', '=', '1,' . $company->id)
            ->sortBy($sortby);
    }

    return Auth::user()->actionLogs
        ->where('activity_key', '=', '1,' . $company->id)
        ->sortByDesc($sortby);

}

This is my Vue component to get the data from the controller. I know the template code works, because it worked fine when I sent it dummy data before pulling the data from the controller.

<style scoped>
.action-link {
    cursor: pointer;
}

.m-b-none {
    margin-bottom: 0;
}
</style>

<template>
<div class="table-responsive">
    <table class="table table-striped table-sm">
        <thead>
            <tr>
                <th><a id="sortby-date" class="action-nav" href="?sortby=date&sortdirection=desc">Date</a></th>
                <th><a id="sortby-company" class="action-nav" href="?sortby=company&sortdirection=desc">Company</a></th>
                <th><a id="sortby-name" class="action-nav" href="?sortby=name&sortdirection=desc">Name</a></th>
                <th><a id="sortby-communication-type" class="action-nav" href="?sortby=communication-type&sortdirection=desc">Communication Type</a></th>
                <th><a id="sortby-contact" class="action-nav" href="?sortby=contact&sortdirection=desc">Contact</a></th>
                <th><a id="sortby-subject" class="action-nav" href="?sortby=subject&sortdirection=desc">Subject</a></th>
                <th><a id="sortby-action" class="action-nav" href="?sortby=action&sortdirection=desc">Comment/Action Item</a></th>
                <th>Archive</th>
                <!-- check if admin?? -->
                    <th><a id="sortby-assigned-to" class="action-nav" href="?sortby=date&sortdirection=desc">Assigned To</a></th>
                <!-- /check if admin?? -->
            </tr>
        </thead>
        <tbody v-if="actions.length > 0">
            <tr v-for="action in actions">
                <td>
                    {{ action.string_date }}
                </td>
                <td>
                    {{ action.company_name }}
                </td>
                <td>
                    {{ action.name }}
                </td>
                <td>
                    {{ action.communication_type }}
                </td>
                <td>
                    {{ action.contact }}
                </td>
                <td>
                    {{ action.status }}
                </td>
                <td>
                    {{ action.action_item }}
                </td>
                <td>
                    <input type="checkbox" :id="'archive-' + action.id" class="archive" :name="'archive-' + action.id">
                </td>
                <td :id="'record-' + action.id" class="assigned-to">
                    {{ action.assigned_to }}
                </td>
            </tr>
        </tbody>
    </table>
    <p id="add-action" style="text-align: center;">
      <button id="action-log-add" class="btn btn-sm btn-primary edit">Add Item</button>
      <button id="action-log-edit" class="btn btn-sm btn-danger edit">Edit Items</button>
    </p>
</div>
</template>

<script>
export default {
    data() {
        return {
            actions: []
        }
    },
    methods: {
        getActionLogs(location) {

            var company = location.split("/");
            company = company[company.length - 1];

            axios.get('/action-log/' + company)
                 .then(response => {

                    this.actions = response.data;                        
                    console.log(this.actions);

                 })
                 .catch(error => {
                    console.log('error! ' + error);
                 });
        }
    },
    mounted() {
        this.getActionLogs(window.location.href);
    }
}
</script>

This is the output I get in the browser console

    {…}
?
    1: Getter & Setter
?
    2: Getter & Setter
?
    3: Getter & Setter
?
    4: Getter & Setter
?
    5: Getter & Setter
?
    6: Getter & Setter
?
    7: Getter & Setter
?
    8: Getter & Setter
?
    9: Getter & Setter
?
    10: Getter & Setter
?
    __ob__: Object { value: {…}, dep: {…}, vmCount: 0 }
?
    <prototype>: Object { … }

I was expecting to see the normal array of data that gets returned, but this is what shows up instead and then won't update the component with the data. I'm new to Vue, so maybe there's something really easy I missing, but I can't seem to figure this out.

 Answers

90

Writing up my comments above as a sort of canonical answer to this as it keeps coming up...

What you're looking at is how Vue proxies your data to make it reactive. This is because you're using console.log() on a Vue instance data property.

When you assign values to a data property, it is transformed to an observable so Vue can treat it reactively. I suggest you forget about trying to console.log() anything assigned to this and use the Vue Devtools browser extension to inspect your components and their data if you're having trouble rendering the response.

Please note, there is nothing wrong here.

Wednesday, March 31, 2021
 
VieStar
answered 7 Months ago
63

Getters and setters are auto-generated in Kotlin. If you write:

val isEmpty: Boolean

It is equal to the following Java code:

private final Boolean isEmpty;

public Boolean isEmpty() {
    return isEmpty;
}

In your case the private access modifier is redundant - isEmpty is private by default and can be accessed only by a getter. When you try to get your object's isEmpty property you call the get method in real. For more understanding of getters/setters in Kotlin: the two code samples below are equal:

var someProperty: String = "defaultValue"

and

var someProperty: String = "defaultValue"
    get() = field
    set(value) { field = value }

Also I want to point out that this in a getter is not your property - it's the class instance. If you want to get access to the field's value in a getter or setter you can use the reserved word field for it:

val isEmpty: Boolean
  get() = field

If you only want to have a get method in public access - you can write this code:

var isEmpty: Boolean
    private set 

due to the private modifier near the set accessor you can set this value only in methods inside your object.

Thursday, June 3, 2021
 
jwegner
answered 5 Months ago
17

Pre-C# 6

I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.

Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:

public string Foo { get; private set; }

which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:

private readonly string foo;
public string Foo { get { return foo; } }

You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.

C# 6

Hooray, we finally have proper read-only automatically implemented properties:

// This can only be assigned to within the constructor
public string Foo { get; }

Likewise for read-only properties which do need to do some work, you can use member-bodied properties:

public double Area => height * width;
Sunday, June 27, 2021
 
OMGKurtNilsen
answered 4 Months ago
86

SOLUTION:

The code above was correct. What was missing was adding the proper responseType as arraybuffer.

I got scared by those ???? inside the response, and that was misleading me. Those question marks were just okay since pdf is a binary data and is meant to be read by a proper reader.

THE ARRAYBUFFER:

And arraybuffer is precisely used to keep binary data.

This is the definition from the mozilla website:

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

And the ResponseType string indicates the type of the response. By telling its an arraybuffer, it then treats the data accordingly.

And just by adding the responseType I managed to properly download the pdf file.

THE CODE:

This is corrected Vue code (exactly as before, but with the addition of the responseType):

downloadFile() {
  this.$http.get(this.appApiPath + '/testpdf', {responseType: 'arraybuffer'})
    .then(response => {
      let blob = new Blob([response.data], { type: 'application/pdf' })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'test.pdf'
      link.click()
    })
}

EDIT:

This is a more complete solution that take into account other browsers behavior:

downloadContract(booking) {
  this.$http.get(this.appApiPath + '/download_contract/' + booking.id, {responseType: 'arraybuffer'})
    .then(response => {
      this.downloadFile(response, 'customFilename')
    }, response => {
      console.warn('error from download_contract')
      console.log(response)
      // Manage errors
      }
    })
},

downloadFile(response, filename) {
  // It is necessary to create a new blob object with mime-type explicitly set
  // otherwise only Chrome works like it should
  var newBlob = new Blob([response.body], {type: 'application/pdf'})

  // IE doesn't allow using a blob object directly as link href
  // instead it is necessary to use msSaveOrOpenBlob
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(newBlob)
    return
  }

  // For other browsers:
  // Create a link pointing to the ObjectURL containing the blob.
  const data = window.URL.createObjectURL(newBlob)
  var link = document.createElement('a')
  link.href = data
  link.download = filename + '.pdf'
  link.click()
  setTimeout(function () {
    // For Firefox it is necessary to delay revoking the ObjectURL
    window.URL.revokeObjectURL(data)
  }, 100)
},
Monday, August 2, 2021
 
steros
answered 3 Months ago
62

actually HTTP PUT is not recognized by html standard. try to do hack like so:

saveProfile() {
    axios.post('/api/pegawai/' + this.id, { // <== use axios.post
         data: this.data,
         _method: 'patch'                   // <== add this field
    })
    .then(function (response) {
         console.log(response);
    })
    .catch(function (error) {
         console.log(error);            
    });
}
Friday, August 6, 2021
 
FyodorX
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share