Vue js model binding for jQuery date picker - javascript

I am using jQuery date picker and its working perfectly. I am in Vue component. when I click the date input field it shows date picker but when I choose one date and see the result in the console I got nothing. Date is not bind.
<form #submit.prevent="search()">
<div class="card">
<div class="card-body">
<div class="card-header"></div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<input type="text" v-model="date" class="form-control" id="datepicker" >
</div>
<div class="col-md-4">
<button class="btn btn-primary" >Search</button>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
export default {
data(){
return{
date:''
}
},
mounted() {
console.log('Component mounted.')
},
methods:{
search(){
//I want to get user chooses date here so that I can send to endpoint
console.log(this.date)//got nothing here
},
},
}
</script
when i click the search button , i should get the date in console but i got nothing, How to get current selected date by user? Thank you

You can bind the input inside mounted hook with the jquery date picker.
new Vue({
el: '#app',
data() {
return {
date: ''
}
},
mounted() {
console.log('Component mounted.');
let selfInstance = this;
$('#datepicker').datepicker({
onSelect: function(selected, datePicker) {
selfInstance.date = selected;
}
});
},
methods: {
search() {
//I want to get user chooses date here so that I can send to endpoint
console.log(this.date) //got nothing here
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<form id="app" #submit.prevent="search">
<div class="card">
<div class="card-body">
<div class="card-header"></div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<input type="text" v-model="date" class="form-control" id="datepicker">
</div>
<div class="col-md-4">
<button class="btn btn-primary">Search</button>
</div>
</div>
</div>
</div>
</div>
</form>
Note: this.date will not work inside the jquery blocks. So an instance should be defined to assign with vue.

Related

How to hide slotted element before rendering the vue template in vueJs 3?

See this images
i dont want to display here those elements
See the Below code sample
sample.blade.php
<create-form id= "create_form" title="Sample Form" >
<div class="col-md-6">
<label class="form-label" for="multicol-username">Username</label>
<input type="text" id="multicol-username" class="form-control" placeholder="john.doe" name="ma_user_id" data-type="varchar" required>
</div>
<div class="col-md-6">
<label class="form-label" for="multicol-email">Email</label>
<div class="input-group input-group-merge">
<input type="text" id="multicol-email" class="form-control" placeholder="john.doe" aria-label="john.doe" aria-describedby="multicol-email2" name="password" data-editmode="false" data-editname="email">
<span class="input-group-text" id="multicol-email2">#example.com</span>
</div>
</div>
</create-form>
createForm.vue
<template>
<div class="card mb-4" v-show="showForm">
<h5 class="card-header">{{title}}</h5>
<form class="card-body" id="createForm" enctype="multipart/form-data" ref="createForm">
<div class="row g-3">
<slot></slot>
<div class="pt-4">
<button type="submit" class="btn btn-primary me-sm-3 me-1" id="save_return">Submit</button>
<button type="reset" class="btn btn-label-secondary" #click="hideForm">Cancel</button>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
props: ['title'],
setup() {},
data() {
return {
}
},
created() {
},
mounted() {
},
methods: {
},
}
</script>
app.js
require('./bootstrap')
import { createApp } from 'vue'
import createForm from './components/createForm';
const app = createApp({})
app.component('create-form', createForm);
app.mount('#app')
It sounds like you want the template that's rendered by the php backend to not be visible until vue is able to handle it, though I'm not 100% sure that's the case.
If that is the case, you could use the v-cloak directive
This directive is only needed in no-build-step setups.
When using in-DOM templates, there can be a "flash of un-compiled templates": the user may see raw mustache tags until the mounted component replaces them with rendered content.
v-cloak will remain on the element until the associated component instance is mounted. Combined with CSS rules such as [v-cloak] { display: none }, it can be used to hide the raw templates until the component is ready.
<create-form id="create_form" title="Sample Form" v-cloak>
...
<style>
[v-cloak] { display: none }
</style>

Amount using input

I just started my journey in vue, how to make the input data take a number into itself, and then display it in a variable, and if you enter 2 times, then add them up.
<template>
<div class="portfel">
<div class="profile">
<div class="content__prof">
<div class="ico__prof"><img src="" alt=""></div>
<div class="buttom__prof">
<input id="txtName" #keyup.enter="addMessage" v-model="myMoney" type="text">
<button #click="addMoney">Sum</button>
</div>
<div class="value__prof">
<div>$: {{myMoney}}</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
myMoney:null,
dollar:0
}
},
methods:{
addMomey(){
this.myMoney.push(this.myMoney)
}
}
}
I tried to do it, but it turns out just a direct transfer to a variable
Check this out:
<script>
export default {
data() {
return {
myMoney: 0,
dollar: 0
}
},
methods: {
addMoney() {
this.dollar += this.myMoney
}
}
}
</script>
<template>
<input v-model.number="myMoney" />
<button #click="addMoney">Add
</button>
<div>
dollar: {{this.dollar}}
</div>
</template>
If you want to use enter, wrap it in a form and listen for #submit.prevent, like this:
<form #submit.prevent="addMoney">
<input v-model.number="myMoney" />
<button type="submit">Add</button>
</form>

Can't get weather data from opendweathermap using Vue.js

I want to create a simple weather report website using Vue.js, I just learned this framework and had accessed public data before. But this time I am stuck.
There are two versions of methods I have tried to get data.
var app = new Vue({
el: "#weather",
data: {
city: '',
weather:[],
date: new Date().toDateString(),
greeting:''
},
methods: {
//method 1
getData: function () {
var city = this.city
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6",
function (data) {
console.log(data)
});
},
//method 2
getData: function () {
$("#search").keypress(function (e) {
if (e.which == 13) {
var city = $("#search").val();
if (city != " ") {
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6";
console.log(url);
}
$.getJSON(url, function (data) {
this.weather = data.weather;
console.log(data);
this.returnGreeting();
})
}
})
},
}
}
});
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left"><h2>{{date}}</h2></div>
<div class="float-right" ><h3 id="time"></h3></div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in data">
<p>
{{data}}
</p>
</div>
<ul class="list-group list-group-flush">
<!-- <li class="list-group-item">{{data.weather[0].main}}</li>
<li class="list-group-item">{{data.weather[0].description}}</li> -->
</ul>
</div>
</div>
<!-- vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I got an error :
[Vue warn]: Property or method "data" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
Consider data to be your model. Don't reference data directly in your view, reference properties that are on the model instead.
So instead of <div>{{data.city}}</div> use <div>{{city}}</div>
var app = new Vue({
el: "#weather",
data() {
return {
city: '',
weather: [],
date: new Date().toDateString(),
greeting: ''
};
},
methods: {
getData() {
fetch("http://api.openweathermap.org/data/2.5/weather?q=" + this.city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6")
.then(res => res.json())
.then(data => {
this.weather = data.weather;
});
}
}
});
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left">
<h2>{{date}}</h2>
</div>
<div class="float-right">
<h3 id="time"></h3>
</div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in weather">
<p>
{{d}}
</p>
</div>
<ul class="list-group list-group-flush"></ul>
</div>
</div>
<!-- vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I found out what caused the issues:
I need to define data in data, as I reference data directly in my html page, but this is optional.
Turns out there is a slim jQuery version from bootstrap that overrides the min jQuery. And $.getJSON() needs min jQuery.
looks like zero beat me to it, but here's a version using jquery call
the issue is, as mentioned in comment, that data.data is not defined. so define data inside data, and assign result to this.data. However, because it's inside a function and the scope changes, you need to store scope using var that = this and use that.data = data to assign result
dom:
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left"><h2>{{date}}</h2></div>
<div class="float-right" ><h3 id="time"></h3></div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in data">
<p>
{{d}}
</p>
</div>
<ul class="list-group list-group-flush">
</ul>
</div>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Script:
var app = new Vue({
el: "#weather",
data: {
city: '',
weather:[],
date: new Date().toDateString(),
greeting:'',
data: null,
},
methods: {
//method 1
getData: function () {
var that = this;
var city = this.city
console.log('getData')
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6",
function (data) {
console.log(data)
that.data = data;
});
},
}
});
Here is an example fiddle.

Vue.js dynamic element creation with localStorage

I'm completely new to Vue and I can't understand the proper way to render components with dynamic values in Vue.js.
So I have this code below :
new Vue({
el: "#notes",
data: {
title: "",
body: ""
},
methods: {
add: function() {
localStorage.setItem($("#title").val(), $("#body").val());
location.reload(true);
},
clear: function() {
localStorage.clear();
location.reload(true);
}
},
created: function() {
for (i = 0; i < localStorage.length; i++) {
this.title = localStorage.key(i);
this.body = localStorage.getItem(localStorage.key(i));
}
}
});
<div id="notes">
<div class="container">
<div class="form-group">
<label for="title">Enter title</label>
<input class="form-control" id="title"/>
</div>
<div class="form-group">
<label for="body">Enter body</label>
<textarea class="form-control" id="body"></textarea>
</div>
<div class="form-group">
<button class="btn btn-primary" #click="add">Add</button>
</div>
<div class="card" style="width:18rem;" v-for="i in localStorage">
<div class="card-body">
<h5 class="card-title">{{title}}</h5>
<p class="card-text">{{body}}</p><a class="card-link" #click="clear">Delete</a>
</div>
</div>
</div>
</div>
And I can't figure out why does this code renders the elements with the same values, I mean if I have two values in localStorage it renders two elements with the value of the last one on localStorage.
Maybe there's some problem with the loop on created? I need some help with understanding the Vue rendering and fixing my function
CodePen
Thank you very much for spending your precious time with my issue! Thank you for any help!
You have one title variable and one body variable. It can't store two values in one variable, so the second overwrites the first. You need arrays.

Issues rendering handlebars to HTML

When I render my handlebars template in html, it looks like it's essentially skipping filling in the "handle bars" portion. I'm essentially printing messages with a title and content, and I'm using a "!each" helper to display all of my messages. I originally thought it was because it was because it was escaping the html around it, so I tried using a triple handle bar {{{ on each part however using the each helper with the triple stash gave me an error. Am I possibly using the handlebars incorrectly?
the typescript I used to render the HTML and my handlebars template is below:
public static refreshData(data: any) {
$("#indexMain").html(Handlebars.templates['main.hbs'](data));
//helper function for upvote button
Handlebars.registerHelper('getUButton', function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default up-button' id='u" + id + "'>Upvote</button>"
);
});
//helper function for downvote button
Handlebars.registerHelper("getDButton", function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default down-button' id='d" + id + "'>DownVote</button>"
);
});
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
}
console.log("context:")
console.log(context);
// Pass data to the template
var theCompiledHtml = theTemplate(context);
console.log(theCompiledHtml);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
//add all click handlers
//get all buttons with id starting with u and set the click listerer
$(".up-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.upvote(id)
});
//get all buttons with id starting with d and set the click listerer
$(".down-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.downvote(id)
});
}
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
<div class="btn-group btn-group-xs" role="group" aria-label="upvote">
{{getUButton id}}
</div>
<div class="btn-group btn-group-xs" role="group" aria-label="downvote">
{{getDButton id}}
</div>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
Okay, then it is likely the data provided to your template is not in the correct form. Here's a working snippet (with non-essentials stripped out). The data passed to your refreshData template must be an array. Make sure it isn't an object containing an array.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script>
let refreshData = (data) => {
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
};
console.log("context:", context);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
}
$(() => {
var data = [
{ likeCount: 3, title: 'My Title', content: 'Some content'},
{ likeCount: 0, title: 'My 2nd Title', content: 'Some other content'}
];
refreshData(data);
})
</script>
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
</body>
</html>
When I am faced with issues like this, I eliminate different things until I either get clarity or something I removed fixes the problem. Now I have isolated where the problem lies. In your situation, the issue is likely the data being passed so verify that. Then try stripping out your helpers to see if they are causing issues.

Categories