Vue.filter is not calling while HTML rendering - vue.js

I am new to Vue.js
While rendering the html, I am invoking a Vue.filter. It should show a date in another format.
Below is my js file :
var details = new Vue({
el: '#ajax-article-detail',
data: {
message: 'Hello Vue.js!'
},
methods: {
showName: function() {
console.log('Calling showName...');
return 'Im Event';
}
}
});
Vue.filter('parseDate', function(date, format) {
if (date) {
//console.log(moment(String(date)).format(format));
return moment(String(date)).format(format);
}
});
and in html, I am calling like {{${start_date} | parseDate('ddd, Do MMM YYYY')}}
and as a response, I am getting same statement.
means, I am getting {{${start_date} | parseDate('ddd, Do MMM YYYY')}} as it is in html.
Can anyone please suggest what I did wrong ?
Thank you.

I have changed your code by adding the filter property within the Vue component creation.
var details = new Vue({
el: '#ajax-article-detail',
data: {
message: 'Hello Vue.js!'
},
methods: {
showName: function() {
console.log('Calling showName...');
return 'Im Event';
}
},
filters: {
parseDate: function(date, format) {
console.log('value passed: ' + date); //check the browser console if it is passed
if (date) {
//console.log(moment(String(date)).format(format));
return moment(String(date)).format(format);
}
}
});
Then use the filter like this-
{{2018-12-19 16:46:00 | parseDate('<your_date_format>') }}
However, you need to check if you are passing the value correctly. Try passing some hard coded string value first and check the console window.

Related

Vuejs: listen to props changes and use it

I am developing a project using Vue JS and I need to watch the props changes and call it inside a <span>.
I have used watch() and it shows that the props values are assigned.
But when I call it inside the <span> the value is not showing.
props: ['verifyText', 'verifyValue', 'profileId', 'logged', 'verifyType', 'status'],
watch: {
verifyText: function () { // watch it
this.verify_text = this.verifyText;
},
verifyValue: function () {
this.verify_value = this.verifyValue;
},
verifyType: function () {
this.verify_type = this.verifyType;
}
},
data() {
return {
verify_type: this.verifyType,
verify_text: this.verifyText,
verify_value: this.verifyValue,
}
},
//using inside span
<span>{{verify_text}}</span>
Receive and insert new data that changes from 'watch'
Try this.
props: ['verifyText', 'verifyValue', 'profileId', 'logged', 'verifyType', 'status'],
watch: {
verifyText: function (new_value) {
this.verify_text = new_value;
}
},
data() {
return {
verify_text: this.verifyText,
}
},
//using inside span
<span>{{verify_text}}</span>
I solved this issue by watching the verify_text in the parent component.
'verify_text': function (value) {
this.verify_text = value;
},
Same for the verify_type and verify_value
Thank you all for replying.

Disable date if selected first time in vuejs

data() {
return {
datePickerOptions: {
disabledDate(date) {
// console.log(form.installation_date); // undefined form
return date < this.form.ins_date ? this.form.ins_date : new Date();
},
},
}
This is saying form undefined i can understand can't initiaize form input inside data return how can i achieve this. disable other date if greater than first input date
please guide
As I said in my comment, you can't have a function returning something in your data so you have to shift your logic somewhere else. You can put that function in your methods:
data() {
return {
datePickerOptions: {
disabledDate: this.isDateDisabled
},
// rest of data
...
methods: {
isDateDisabled(date) {
return date < new Date(this.ruleForm.date1);
},

Vue.js | Filters is not return

I have a problem.
I am posting a category id with http post. status is returning a data that is true. I want to return with the value count variable from the back. But count does not go back. Return in function does not work. the value in the function does not return from the outside.
category-index -> View
<td>{{category.id | count}}</td>
Controller File
/**
* #Access(admin=true)
* #Route(methods="POST")
* #Request({"id": "integer"}, csrf=true)
*/
public function countAction($id){
return ['status' => 'yes'];
}
Vue File
filters: {
count: function(data){
var count = '';
this.$http.post('/admin/api/dpnblog/category/count' , {id:data} , function(success){
count = success.status;
}).catch(function(error){
console.log('error')
})
return count;
}
}
But not working :(
Thank you guys.
Note: Since you're using <td> it implies that you have a whole table of these; you might want to consider getting them all at once to reduce the amount of back-end calls.
Filters are meant for simple in-place string modifications like formatting etc.
Consider using a method to fetch this instead.
template
<td>{{ categoryCount }}</td>
script
data() {
return {
categoryCount: ''
}
},
created() {
this.categoryCount = this.fetchCategoryCount()
},
methods: {
async fetchCategoryCount() {
try {
const response = await this.$http.post('/admin/api/dpnblog/category/count', {id: this.category.id})
return response.status;
} catch(error) {
console.error('error')
}
}
}
view
<td>{{count}}</td>
vue
data() {
return {
count: '',
}
},
mounted() {
// or in any other Controller, and set your id this function
this.countFunc()
},
methods: {
countFunc: function(data) {
this.$http
.post('/admin/api/dpnblog/category/count', { id: data }, function(
success,
) {
// update view
this.count = success.status
})
.catch(function(error) {
console.log('error')
})
},
},

Getting reactivity from watch in Vue.js

Trying to make a component in Vue.js, which first shows image via thumbnail, loading full image in background, and when loaded, show full image.
The thing which does not work, component does not react on change of showThumb flag in watch section. What is wrong?
Vue.component('page-image',
{
props: ['data'],
template:
'<img v-if="showThumb == true" v-bind:src="thumbSrc"></img>'+
'<img v-else v-bind:src="fullSrc"></img>',
data: function()
{
return { thumbSrc: '', fullSrc: '', showThumb: true };
},
watch:
{
data: function()
{
this.thumbSrc = data.thumbImg.url;
this.fullSrc = data.fullImg.url;
this.showThumb = true;
var imgElement = new Image();
imgElement.src = this.fullSrc;
imgElement.onload = (function()
{
this.showThumb = false; // <<-- this part is broken
} );
}
}
} );
Note: there is a reason why I do it via 2 img tags - this example is simplified.
Your onload callback will have a different scope than the surrounding watch function, so you cannot set your data property like this. Change it to an arrow function to keep scope:
imgElement.onload = () =>
{
this.showThumb = false;
};
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

My Dijit DateTimeCombo widget doesn't send selected value on form submission

i need to create a Dojo widget that lets users specify date & time. i found a sample implementation attached to an entry in the Dojo bug tracker. It looks nice and mostly works, but when i submit the form, the value sent by the client is not the user-selected value but the value sent from the server.
What changes do i need to make to get the widget to submit the date & time value?
Sample usage is to render a JSP with basic HTML tags (form & input), then
dojo.addOnLoad a function which selects the basic elements by ID, adds dojoType
attribute, and dojo.parser.parse()-es the page.
Thanks in advance.
The widget is implemented in two files. The application uses Dojo 1.3.
File 1: DateTimeCombo.js
dojo.provide("dojox.form.DateTimeCombo");
dojo.require("dojox.form._DateTimeCombo");
dojo.require("dijit.form._DateTimeTextBox");
dojo.declare(
"dojox.form.DateTimeCombo",
dijit.form._DateTimeTextBox,
{
baseClass: "dojoxformDateTimeCombo dijitTextBox",
popupClass: "dojox.form._DateTimeCombo",
pickerPostOpen: "pickerPostOpen_fn",
_selector: 'date',
constructor: function (argv) {},
postMixInProperties: function()
{
dojo.mixin(this.constraints, {
/*
datePattern: 'MM/dd/yyyy HH:mm:ss',
timePattern: 'HH:mm:ss',
*/
datePattern: 'MM/dd/yyyy HH:mm',
timePattern: 'HH:mm',
clickableIncrement:'T00:15:00',
visibleIncrement:'T00:15:00',
visibleRange:'T01:00:00'
});
this.inherited(arguments);
},
_open: function ()
{
this.inherited(arguments);
if (this._picker!==null && (this.pickerPostOpen!==null && this.pickerPostOpen!==""))
{
if (this._picker.pickerPostOpen_fn!==null)
{
this._picker.pickerPostOpen_fn(this);
}
}
}
}
);
File 2: _DateTimeCombo.js
dojo.provide("dojox.form._DateTimeCombo");
dojo.require("dojo.date.stamp");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit._Calendar");
dojo.require("dijit.form.TimeTextBox");
dojo.require("dijit.form.Button");
dojo.declare("dojox.form._DateTimeCombo",
[dijit._Widget, dijit._Templated],
{
// invoked only if time picker is empty
defaultTime: function () {
var res= new Date();
res.setHours(0,0,0);
return res;
},
// id of this table below is the same as this.id
templateString:
" <table class=\"dojoxDateTimeCombo\" waiRole=\"presentation\">\
<tr class=\"dojoxTDComboCalendarContainer\">\
<td>\
<center><input dojoAttachPoint=\"calendar\" dojoType=\"dijit._Calendar\"></input></center>\
</td>\
</tr>\
<tr class=\"dojoxTDComboTimeTextBoxContainer\">\
<td>\
<center><input dojoAttachPoint=\"timePicker\" dojoType=\"dijit.form.TimeTextBox\"></input></center>\
</td>\
</tr>\
<tr><td><center><button dojoAttachPoint=\"ctButton\" dojoType=\"dijit.form.Button\">Ok</button></center></td></tr>\
</table>\
",
widgetsInTemplate: true,
constructor: function(arg) {},
postMixInProperties: function() {
this.inherited(arguments);
},
postCreate: function() {
this.inherited(arguments);
this.connect(this.ctButton, "onClick", "_onValueSelected");
},
// initialize pickers to calendar value
pickerPostOpen_fn: function (parent_inst) {
var parent_value = parent_inst.attr('value');
if (parent_value !== null) {
this.setValue(parent_value);
}
},
// expects a valid date object
setValue: function(value) {
if (value!==null) {
this.calendar.attr('value', value);
this.timePicker.attr('value', value);
}
},
// return a Date constructed date in calendar & time in time picker.
getValue: function() {
var value = this.calendar.attr('value');
var result=value;
if (this.timePicker.value !== null) {
if ((this.timePicker.value instanceof Date) === true) {
result.setHours(this.timePicker.value.getHours(),
this.timePicker.value.getMinutes(),
this.timePicker.value.getSeconds());
return result;
}
} else {
var defTime=this.defaultTime();
result.setHours(defTime.getHours(),
defTime.getMinutes(),
defTime.getSeconds());
return result;
}
},
_onValueSelected: function() {
var value = this.getValue();
this.onValueSelected(value);
},
onValueSelected: function(value) {}
});
It sounds like you want to use getValue. The convention now is to use _getValueAttr and then call attr("value") but I think that started in Dojo 1.4 and this code would need to be ported to use those new patterns.
Noe that value should be a Javascript Date object which would best be sent to the server using dojo.date.stamp.toISOString()
This began to work fine after i added a "serialize" method to DateTimeCombo.js which builds exactly the output format i want.
This seems odd to me, since there is already a serialize implementation in _DateTimeTextBox.js that should output the value in the required ISO format.