I use in my project element UI autocomplete component.
When the input raises no result, I want to show a no results message.
In other projects I had it as an option in the suggest box (which is NOT selectable):
However, with element-ui autocomplete, after the searching icon disappears, the drop-down disappears as well:
With this component I do not manage to do so. Any idea?
My code looks like this:
Template:
<el-form ref="addressForm" :inline="true" :model="formData">
<el-form-item prop="city">
<el-autocomplete
class="inline-input"
v-model="formData.cityInput"
:fetch-suggestions="getCities"
placeholder="City"
:trigger-on-focus="false"
:clearable="true"
#select="handleSelectCity"
#clear="clearCity"
size="small"
></el-autocomplete>
</el-form-item>
:
:
<el-form-item>
<el-button type="primary" #click="onSubmit" size="small">
Search
</el-button>
</el-form-item>
</el-form>
Script:
export default {
data() {
return {
formData: {
cityInput: "",
city: "",
:
:
},
}
},
methods: {
getCities(query, callback) {
this.clearCity();
// Ajax call to obtain results for autocomplete
axios.get(
"/cities", {
query: query
})
.then(
response => {
callback(response.data);
}
);
},
handleSelectCity(item) {
this.formData.city = item.value;
},
clearCity() {
this.formData.city = "";
},
:
:
:
}
};
PHP code: (Laravel)
public function getCities($query)
{
$res = DB::connection('mainDb')
->table('offices')
->where('city', 'like', $query . '%')
->select('city AS value')
->distinct()
->get();
return $res;
}
You can achieve this behaviour with v-select. There is a filtering option so you can either select option or type it down with autocomplete.
There are two attributes to control "no-result" case: no-match-text when filtering gave no result and no-data-text when there is no options in select.
I tried el-select and it works good with "no matched data".But its remote-method function isn't smart enough without callback parameter if you want to pass a function to it from outside component.
So,I have to try codepen.io/boussadjra/pen/ZEGvGNm, use the blur method to clear no matched data, and it works like the el-select.
Related
I am migrating my current application from Laravel Livewire to Laravel InertiaJS VueJS. Currently I am stuck at setting the per page count from the front end and paginate the data accordingly. Currently I am using Laravel's default pagination along with the custom pagination component for VueJS and it works seamlessly. I just want to set the $per_page as per the input, the variable is set to 5 by default, in the index method of the controller. Below is the code structure and the logic. Please help me achieve this in the way InertiaJS is meant to be used.
UserController.php
public function index(Request $request)
{
$per_page = \Request::get('per_page') ?: 5;
$query = User::select('id', 'name', 'email', 'role_id', 'created_at');
$users = $query->paginate($per_page);
return Inertia::render('Backend/Management/AudienceManagement/Users/Index', [
'users' => $users
]);
}
Users/Index.vue
<template>
<input-group borderless paddingless inline>
<input-select #change="setPerPage($event)" id="perPage" placeholder="Per Page">
<option value="5">5</option>
<option value="10">10</option>
</input-select>
</input-group>
</template>
<script>
import {
Inertia
} from '#inertiajs/inertia'
export default {
props: {
users: {
type: Object
}
},
data() {
return {
sortField: '',
sortDirection: ''
}
},
methods: {
setPerPage(event) {
console.log(event.target.value);
this.users.per_page = event.target.value;
Inertia.reload({
only: ['users.data']
});
},
}
}
</script>
My Greeting.
To put in context, my purpose of asking this question is to be able to render a child component inside a form based on the selected option of the <app-selector> Vue component as simple and silly as that.
For the sake of simplicity. I've made a snippet down here to expose what I'm trying to figure out.
Basically, the aim is to get the component name to be rendered by using the computed property cardTypeComponent. However, I want to fathom the way cardTypeComponent is working, since I cannot see why, in one hand, the first return (return this.form) is giving the object (this.form) with the property I want (card_type) but on the other hand the second return (return this.form.card_type ? this.form.card_type + 'Compose' : '') is giving me an empty string, assuming this.form.card_type is undefined when it is clear looking at the first return that, in fact, is not taking it as undefined.
There is way more context, since once the option is selected there is a validation process from the server before setting the value inside this.form object. Moreover, the form interaction is through steps, so once the user select the option he has to click a button to reach the form fields that corresponds to that type card selected, therefore the component is not going to be rendered the very first moment the user selects an option as in the snippet approach. However, it would entangle what I'm asking. Thanks beforehand.
It is better to use the Fiddle link below.
Snippet
var appSelector = Vue.component('app-selector', {
name: 'AppSelector',
template: `<div>
<label for="card_type">Card Type:</label>
<select :name="name" value="" #change="sendSelectedValue">
<option v-for="option in options" :value="option.value">
{{ option.name }}
</option>
</select>
</div>`,
props: {
name: {
required: false,
type: String,
},
options: {
required: false,
type: Array,
}
},
methods: {
sendSelectedValue: function(ev) {
this.$emit('selected', ev.target.value, this.name)
}
}
});
var guessByImageCompose = Vue.component({
name: 'GuessByImageComponse',
template: `<p>Guess By Image Compose Form</p>`
});
var guessByQuoteCompose = Vue.component({
name: 'GuessByQuoteComponse',
template: `<p>Guess By Quote Compose Form</p>`
});
new Vue({
el: '#app',
components: {
appSelector: appSelector,
guessByImageCompose: guessByImageCompose,
guessByQuoteCompose: guessByQuoteCompose,
},
data() {
return {
form: {},
card_types: [
{
name: 'Guess By Quote',
value: 'GuessByQuote'
},
{
name: 'Guess By Image',
value: 'GuessByImage'
}
],
}
},
computed: {
cardTypeComponent: function() {
return this.form; // return { card_type: "GuessByImage" || "GuessByQuote" }
return this.form.card_type ? this.form.card_type + 'Compose' : ''; // return empty string ("") Why?
}
},
methods: {
setCardType: function(selectedValue, field) {
this.form[field] = selectedValue;
console.log(this.form.card_type); // GuessByImage || GuessByQuote
console.log(this.cardTypeComponent); // empty string ("") Why?
}
},
mounted() {
console.log(this.cardTypeComponent); // empty string ("")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form action="#" method="post">
<app-selector
:name="'card_type'"
:options="card_types"
#selected="setCardType"
>
</app-selector>
{{ cardTypeComponent }} <!-- Always empty string !-->
<component v-if="cardTypeComponent !== ''" :is="cardTypeComponent">
</component>
</form>
</div>
https://jsfiddle.net/k7gnouty/2/
You're setting a property on this.form which is not initialized first in data. This means you have run into Vue's change detection caveat. Use Vue.set when setting it:
methods: {
setCardType: function(selectedValue, field) {
Vue.set(this.form, field, selectedValue);
}
}
Alternatively, you could declare the properties first if that works better for you.
How can I set a value input that uses the v-model?
I Googled for this problem but not solved
I have an input like this:
<input type="text" name="customer_email" v-model="form.customer_email" id="email">
I need to set this input value to {{ auth()->user()->email }}
TRY THIS :)
data() {
return {
form: {
customer_email: "",
}
}
},methods:{
user(){
axios.get("api/profile").then(({data})=>{
(this.user = data)
this.form.customer_emeail = this.user.email
})
},
},created(){
this.user();
}
In your controller add this
public function profile()
{
return auth('api')->user();
}
then put this in your api.php
Route::get('profile','YourController#profile');
As you are using two way data binding v-model, you can simply set this value in the vue end.
let app = new Vue({
el:"#app",
data() {
return {
form: {
customer_email: "{{ auth()->user()->email }}",
......
......
}
}
},
......
......
});
I'm new to Vue and I would like some help getting a value from an input field:
In my form I have:
<input type="hidden" id="groupId" value="1">
If I was using jQuery I would do:
var group_id = $('#groupId').val();
However, in Vue I don't know how to bind the hidden field:
<div id="app">
<input type="text" v-model="groupId"> //Where do I put the value?
</div>
new Vue({
el: '#app',
data: {
groupId: //What do I put here to get the field's value?
}
How can I achieve this?
Update to the update: See this answer. Previously updated answer was wrong.
Original answer:
In Vue, you don't get things from the view and put things into the view. Vue does that. You do all manipulations in the viewmodel, and make bindings in the view so that Vue knows how to synchronize it. So you'd bind the input to your model data item:
<input type="hidden" id="groupId" v-model="groupId">
and set its value in your viewmodel:
data: {
groupId: 1
}
I had the same question. I'm working with Vue + Laravel.
For me, the solution was simple after searching and not finding a concrete solution in the Vue documentation.
Simply:
document.getElementById('MyId').value;
Details in → https://www.w3schools.com/jsref/prop_text_value.asp
It is not the most efficient solution, but it works for now!
Greetings.
Working sample of getting value from input field in this case it is hidden type:
<input type="hidden" name="test">
<script>
new Vue ({
created () {
const field = document.querySelector("input[name=test]").value
console.log(field)
}
})
</script>
this code helped me
i hope that this work with you
define the input
<div class="root">
<input type="hidden" ref="groupId" value="1">
<button type="button" v-on:click="get_id()">test</button>
</div>
define the method
new Vue({
el: ".root",
data: {
id: null,
}
methods: {
get_id() {
this.id = this.$refs.groupId.value;
}
}
});
// if you want it displayed on your page, use {{ groupId }}
/* you can get the value by using #change.enter=".." #keypress.enter="getInputValue",
or #input="getInputValue" or #click="getInputValue" using button,
or if it is with a form element, #submit.prevent="getInputValue" */
/* #keypress.enter tracks input but only calls the function when the Enter key
is pressed, #input track changes as it's being entered */
// it is important to use event.preventDefault() when using #change or #keypress
<div id="app">
<input type="text" v-model="groupId">
<p> {{ groupId }} </p>
<button #click="getInputValue">Get Input</button>
</div>
new Vue({
el: '#app',
data: {
groupId: //What do I put here to get the field's value?
// for what to put there, you can use an empty string or null
groupId: "",
},
// to get the value from input field
methods: {
getInputValue: function() {
if(this.groupId !== "") {
console.log(this.groupId);
}
},
}
})
look at this I did it in laravel, vuejs, vuetable2 and children's row, and don't use the v-model:
this.$refs['est_'+id_det].localValue
en VUE:
<div class="col-md-3">
<b-form-select class="form-control selectpicker" :ref="'est_'+props.row.id_detalle_oc"
:value="props.row.id_est_ven" v-on:change="save_estado(props.row.id_detalle_oc)">
<option value="0">Sin estado</option>
<option value="1">Pendiente</option>
<option value="2">Impresa</option>
<option value="3">Lista</option>
</b-form-select>
in methods
methods: {
save_estado:function (id_det){
var url= 'ordenes-compra/guardar_est_ven'
var id_estado = this.$refs['est_'+id_det].localValue
axios.post(url,{
id_det: id_det,
id_est_ven: id_estado,
est_ven: est_ve
}).then(function (response) {
var respuesta= response.data;
if(respuesta == "OK"){
swal({
type: 'success',
title: '¡Éxito!',
text: 'Estado modificado',
confirmButtonText: 'Entendido',
})
}
})
.catch(function (error) {
console.log(error);
});
},
I hope it helps, I've been hanging around for a while.
Regards
Hi you can also try the following:
const input = this.$el.firstElementChild;
in case you are using TypeScript, declare input as:
: HTMLInputElement
Then, you can simply get the value if you do:
input.value
Hope it helps!
Ok, this does the job: document.querySelector('#groupId').getAttribute('value');
I am trying to update the input text field ( Start time ) after the onClick={this.populateDate}. But I get the default value passed to the AJAX call to PHP.
https://jsfiddle.net/adwantgoutam/rg68Lyfk/
<?php header('Access-Control-Allow-Origin: *');
echo "Hello World";
$stime= $_GET['first_name'];
$etime= $_GET['last_name'];
$xyz= $_GET['start_time'];
echo "\n";
echo $stime;
echo "\n";
echo $etime;
echo "\n";
echo $xyz;
?>
Output :
Hello world!
John
Doe
03/11/2016 ( not the updated one after we click date through image onclick ).
var Hello = React.createClass({
render() {
return (
<form onSubmit={this.handleSubmit}>
<input value={this.state.first_name} onChange={this.setFirstName} placeholder="First name"/><br/>
<input value={this.state.last_name} onChange={this.setLastName} placeholder="Last name"/><br/>
<input value={this.state.start_time} onChange={this.setStartTime} placeholder="Start Time" id="demo1" name="stime"/>
<img src="https://rainforestnet.com/datetimepicker/sample/images2/cal.gif" onClick={this.populateDate}/><br/>
<button type="submit">Submit</button>
</form>
)
},
handleSubmit(event) {
event.preventDefault();
var data = this.state;
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8082/PFT/login.php",
data: data,
success: function(data){
alert(data);
//$('#resultip').html(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},
populateDate(){
NewCssCal('demo1','yyyyMMdd','dropdown',true,'24',true);
},
getInitialState() {
return {
first_name: "John",
last_name: "Doe",
start_time: "03/11/2016",
};
},
setStartTime(event) {
console.log( event.target.value)
this.setState({start_time: event.target.value});
}
});
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
I have attached my code in jsfiddle and above is the PHP script. I am not sure where exactly or how to process this. Any help is highly appreciated. Thanks.
I have gone through the date picker library you are using. To make this code work you'll have to add componentDidMount as follows.
componentDidMount(){
document.getElementById('demo1').onchange= this.setStartTime;
}
Then you need to modify you setStartTime function as follows
setStartTime() {
this.setState({start_time: document.getElementById('demo1').value});
}
Because the library is triggering change event programatically(as the value is being changed programmatically). Hence you'll not get the event object.
Though doing so will make your code work, my suggestion will be to use any react library for date-time picker(if you don't have the dependency to use this only) which provide proper configuration as per your requirement. Also try to use refs instead of document.getElement.... which is the react way of interacting with dom.