I have an instance of mounted in Vue, where I’m trying to set a date picker having the starting date depends on a data fed by an ajax response. Let’s say this data property is named start_date
. I run my ajax request via the created instance in Vue.
It’s a little weird when I tried to console log vm.myObject, it shows the correct value start_date
property coming from the ajax response. However, whenever I access the specific property via vm.myObject.start_date
it will show you the default one I’ve created for data binding. My code structure below:
<script> export default { mounted() { const vm = this; console.log(vm.myObject); // this will show the data from ajax response console.log(vm.myObject.start_date); //this will show the default value I set which si the 2017-10-25 }, created() { const self = this; $.ajax({ url: ApiRoutes.paths.GetDealData, data: { id: 1 }, success: function(res) { self.myObject.start_date = res.start_date; } }); }, data() { return { myObject: { start_date: "2017-10-25" } }; } }; </script>
I’m very new to Vue JS, so I’m currently having a hard time handling the data in the component via ajax request. I’ve already tried all the instances included beforeCreate, beforeMount but it didn’t fix my issue still. How can I understand this kind of behavior?
Advertisement
Answer
Your code can’t really work the way you described in your answer. you are doing asynchronous operation (ajax call) and try to print the values right after synchronous operation? nope.
If you want to console.log(response)
, you can do it in your callback function.
If you want to print the value on the page, but show nothing until the value is fetched (asynchronous operation), you can define on your data
an attribute that signal if the fectching process is finished or not. and toggle it inside your callback.
I have edited the code to show how to declare the date-picker
(have to be declared from the template
side.
You have to pass the start_date
as a props (I assume the prop name for the date-picker
is start-date
). when the ajax request is finished, the reactivity of vue will take care of re-rendering of the date-picker
<template> <div> <datePicker :start-date="myObject.start_date" /> </div> </template> <script> export default { created() { $.ajax({ url: ApiRoutes.paths.GetDealData, data: { id: 1 }, success: function(res) { self.myObject.start_date = res.start_date; self.isFetchedFinished = true } }); }, data() { return { startDate: '' }; } }; </script>