Select2 form input not change value with vue - laravel

i need help. So basicly, when i used ordinary select form, i have succeed pass the data. but when i change to select2. Why my select2 not change value like select2 form??
This is with my select form ordinary with success pass data
<template>
<div class="col-md-3 col-sm-4">
<div class="filter-sidebar">
<div class="col-md-12 form-title">
<h2>Find the OPD</h2>
</div>
<form id="search" role="form" class="" #submit.stop.prevent="searchOpdForm" method="post">
<div class="col-md-12 form-group category">
<label class="control-label" for="category">Instansi / OPD</label>
<select id="opd" name="opd" class="form-control" v-model="selectopd.opd">
<option v-for="opd in opds" :key="opd.index" :value="opd.id">{{opd.nama_opd}}</option>
</select>
</div>
<div class="col-md-12 form-group button">
<button type="submit" class="btn tp-btn-primary tp-btn-lg btn-block">Cari</button>
<router-link :to="{name: 'listings'}" class="btn btn-reset"><i class="fa fa-repeat"></i>Reset</router-link>
</div>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
import {API_BASE} from '../Config/config'
export default {
name: 'Sidebar',
data() {
return {
opds: [],
selectopd: {}
}
},
created() {
this.fetchOpds();
},
methods: {
searchOpdForm() {
let urlpost = `${API_BASE}/listings/search/opd`
console.log('submiting')
axios.post(urlpost, this.selectopd)
.then(response => {
this.$router.push({name: 'searchlistingopd', params: {listings: response.data.listings}})
console.log('successful')
})
.catch(error => {
console.log(error)
})
},
fetchOpds() {
let url = `${API_BASE}/get-opds`
axios.get(url)
.then(response => {
this.opds = response.data.opds
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
And this is with example selected id's :
And if i changes to this, and a bit search with select2 form format, and my code is like this
<template>
<div class="col-md-3 col-sm-4">
<div class="filter-sidebar">
<div class="col-md-12 form-title">
<h2>Find the OPD</h2>
</div>
<form id="search" role="form" class="" #submit.stop.prevent="searchOpdForm" method="post">
<div class="col-md-12 form-group category">
<label class="control-label" for="category">Instansi / OPD</label>
<select id="opd" name="opd" class="form-control" v-model="selectopd.opd">
<option v-for="opd in opds" :key="opd.index" :value="opd.id">{{opd.nama_opd}}</option>
</select>
</div>
<div class="col-md-12 form-group button">
<button type="submit" class="btn tp-btn-primary tp-btn-lg btn-block">Cari</button>
<router-link :to="{name: 'listings'}" class="btn btn-reset"><i class="fa fa-repeat"></i>Reset</router-link>
</div>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
import {API_BASE} from '../Config/config'
import jQuery from 'jquery'
let $ = jQuery
require('select2')
export default {
name: 'Sidebar',
data() {
return {
opds: [],
selectopd: {}
}
},
created() {
this.fetchOpds();
},
mounted() {
$("#opd").select2()
},
methods: {
searchOpdForm() {
let urlpost = `${API_BASE}/listings/search/opd`
console.log('submiting')
axios.post(urlpost, this.selectopd)
.then(response => {
this.$router.push({name: 'searchlistingopd', params: {listings: response.data.listings}})
console.log('successful')
})
.catch(error => {
console.log(error)
})
},
fetchOpds() {
let url = `${API_BASE}/get-opds`
axios.get(url)
.then(response => {
this.opds = response.data.opds
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
Now when i choose value, it doesn't change anything. Just like this
Am I doing wrong with select2 code to use it in my component? Or i missing something to add like native jquery in ordinary?

You could change
<select id="opd" name="opd" class="form-control" v-model="selectopd.opd">
for
<select id="opd" name="opd" class="form-control" v-model="selectopd">

Related

Dynamic select box data binding on vuejs

i have questions about data binding in vuejs and i hope everyone here can help me to solve this problem.
I'm in the stage of learning to use vuejs with laravel. I have problems doing data bindings in the data editing process, I can not display any information in the select box.
Next I include the data response that i want to display and the code.
data response
{
"data":{
"id":101,
"kode":"B100",
"nama":"Bendung Jules Rutherford",
"desa":{
"id":"5103050018",
"district_id":"5103050",
"name":"BONGKASA PERTIWI",
"district":{
"id":"5103050",
"city_id":"5103",
"name":"ABIANSEMAL",
"city":{
"id":"5103",
"province_id":"51",
"name":"KABUPATEN BADUNG",
"province":{
"id":"51",
"name":"BALI",
}
}
}
}
}
}
and this is the code :
<template>
<div>
<div v-if="!loading">
<div class="form-group row">
<label class="col-sm-3">Kode</label>
<div class="col-sm-9">
<input :class="{'is_invalid' : errors.kode}" v-model="bendung.kode" type="text" class="form-control" placeholder="B0001">
<div class="invalid-feedback" v-if="errors.kode">{{ errors.kode[0] }}</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3">Nama</label>
<div class="col-sm-9">
<input :class="{'is-invalid': errors.nama}" v-model="bendung.nama" type="text" class="form-control" placeholder="Bendungan Mengwi">
<div class="invalid-feedback" v-if="errors.nama">{{ errors.nama[0] }}</div>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.provinces }]">
<label class="col-sm-3">Provinsi</label>
<div class="col-sm-9">
<select #change="province" v-model="bendung.desa.district.city.province_id" class="form-control">
<option value="">Pilih Provinsi</option>
<option v-for="province in provinces" :value="province.id">
{{ province.name }}
</option>
</select>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.cities }]">
<label class="col-sm-3">Kota / Kabupaten</label>
<div class="col-sm-9">
<select #change="city" v-model="bendung.desa.district.city_id" class="form-control">
<option value="">Pilih Kota/Kabupaten</option>
<option v-for="city in cities" :value="city.id">
{{ city.name }}
</option>
</select>
</div>
</div>
</div>
<div class="row" v-else>
<div class="col-sm-12">
<content-placeholders>
<content-placeholders-text/>
</content-placeholders>
</div>
</div>
<div class="form-group row">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<a class="btn btn-success" href="#" :disabled="submiting" #click.prevent="update">
<font-awesome-icon :icon="['fas', 'spinner']" v-if="submiting" />
<font-awesome-icon :icon="['fas', 'check']" v-else/>
<span class="ml-1">Perbaharui</span>
</a>
<a href="/sda/bendung" class="btn btn-danger">
<font-awesome-icon :icon="['fas', 'times-circle']" /> Batal</a>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
errors: {},
bendung: {},
provinces: [],
cities:[],
districts: [],
state: {
province: '',
city: '',
district: '',
},
loading: true,
submiting: false
}
},
mounted() {
this.getBendung();
this.getProvinces();
},
methods: {
getBendung() {
this.loading = true;
let str = window.location.pathname;
let res = str.split("/");
axios.get(`${process.env.MIX_WEBSERVICE_URL}/sda/bendung/${res[3]}`)
.then(response => {
this.bendung = response.data.data;
this.state.province = this.bendung.desa.district.city.province_id;
})
.catch(error => {
this.$toasted.global.error('Bendung tidak ditemukan!');
location.href = '/sda/bendung';
})
.then(() => {
this.loading = false;
});
},
getProvinces() {
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/province`).then(response => {
this.provinces = response.data;
}).catch(error => console.error(error));
},
province() {
this.state.city = '';
const params = {
province: this.state.province
}
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/city`, {params}).then(response => {
this.cities = response.data;
}).catch(error => console.error(error));
},
city() {
this.state.district = '';
const params = {
city: this.state.city
};
// /location/district?city=cityId
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/district`, {params}).then(response => {
this.districts = response.data;
}).catch(error => console.error(error));
}
}
}
</script>
<style scoped>
</style>
the result is like this picture.
i want to show city name on select box but i got blank selectbox and when i change the selectbox (e.g provinsi/province), the other selectbox (e.g. kabupaten/kota/city) will change it data.
You could fetch new data when previous data has been changed.
Here is the working example: https://codesandbox.io/embed/vue-template-2zv2o
Have you tried to use the v-bind:key prop within your v-for loop?
v-bind:key="city.id"
or better with an additional index:
v-for="(city, index) in cities"
[...]
v-bind:key="`${index}-${city.id}`"

Reset input on click, vue

I would like to have my text fields empty when I click "add task" button. How could I achieve that?
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask()">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask() {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
}
It's very simple, in the addTask() just add event as parameter and in the end of the function you write: event.target.reset();
Code:
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
And there:
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask(event) {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
event.target.reset();
}
Hope it works for you ; )

VueJs: How to create a select where options come from a query to other model

I'm new on VueJs and I don't know why I have the following problem:
I'm creating a view called Owners.vue where I show pub owners. In UpdateProfile.vue I show the owner data and here is where I have my problem: I'd like to build a select where the options are the possible pubs stored in my table "pubs":
My vue component is as follows:
UpdateProfile.vue
<template>
<confirm title="Edit User" ok="Save user" :show="show"
v-on:save="save"
v-on:close="close">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="User name" v-model="data.name">
</div>
</div>
<div class="field">
<label class="label">Lastname</label>
<div class="control">
<input class="input" type="text" placeholder="last name" v-model="data.lastname">
</div>
</div>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input class="input" type="email" placeholder="email" v-model="data.email">
</div>
</div>
<!--Owner Pubs-->
<div class="field">
<label class="label">Pubs</label>
<div v-for="pub in data.userPubsOwned" class="control">
<input class="input" type="text" placeholder="Pub tapps" v-model="pub.name">
<div class="button is-danger" #click="deletePubFromOwner(pub.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<!--Owner Pubs-->
<!--Add Pubs to Owner-->
<div class="field">
<label class="label">Add new Pub</label>
<div class="select">
<select v-model="pubs">
<option v-for = "pub in pubs" :value="pub.id" >{{pub.name}}</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addPubToOwner()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Tapp</span>
</div>
</div>
<!--Add Pubs to Owner-->
</confirm>
import User from "../../models/user";
export default {
props: {
show: Boolean,
data: Object,
},
data() {
return {
selected: null,
data: new User(),
pubs: [],
pub: new Pub(),
}
},
computed: {
},
methods: {
save() {
this.$emit('save', this.data);
},
close() {
this.$emit('close');
},
hasRootPermissionsAndIsNotRoot() {
return this.CONSTANTS.hasRootPermissions() && this.data.permissions !== this.CONSTANTS.ROOT_USER.permissions;
},
addPubToOwner(){
this.api.post('/owners/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deletePubFromOwner(ownerpub) {
this.api.delete('/owners/' + this.data.id + '/' + ownerpub).then(response => {
this.data = response.data;
});
},
}
}
I just need to show all the pubs stored in my table pub...do I have to create a function? And how it would be?
Thanks a lot for your help!!
Yes, create a method in the mounted() section. I use a similar process to show all of the flavors/prices of a product in a shopping cart. Here is my code that you can use and hopefully extrapolate your answer from:
Mounted function to load upon vue mount
mounted: function() {
this.getPrice();
},
getPrice() function:
getPrice: function(){
axios.post('/getproductinfo', this.$data.model)
.then((response) => {
console.log(response);
this.display_name = response.data.display_name;
this.price = '$' + response.data.price;
})
.catch(error => {
this.errors.record(error.response.data.errors);
});
},
And finally the code in your view blade file
<select class="centerSelect" v-show="!loading && ordering" ref="quantitySelect" v-model="model.id" name="code_id" #change="getPrice">
#foreach ($code as $item)
<option value="{{$item->id}}">{{$item->display_name}}</option>
#endforeach
</select>

In use vee-validate library vue-select element does not work

In vuejs 2.5 application I use vee-validate library ( http://vee-validate.logaretm.com/examples.html ) with inputs like:
<template>
<section>
<form #submit.prevent="validateBeforeSubmit" class="form-horizontal">
<div class="row">
<div class="col-xs-12 form-group">
<label class="col-xs-12 col-sm-4 control-label" for="name">Name<span class="required"> * </span></label>
<div class="col-xs-12 col-sm-8">
<input v-validate="'required|max:255'" v-model="task.name"
:class="{ 'form-control':true, 'input': true, 'text-danger': vueErrorsList.has('name') }" name="name" id="name"
type="text" placeholder="name">
<span v-show="vueErrorsList.has('name')" class="text-danger">{{ vueErrorsList.first('name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
<label class="col-xs-12 col-sm-4 control-label" for="category_id">Category<span class="required"> * </span></label>
<div class="col-xs-12 col-sm-8">
<v-select v-validate="'required'" id="category_id" name="category_id" v-model="selection_category_id" :options=categoriesSelectionList></v-select>
<span v-show="vueErrorsList.has('category_id')" class="text-danger">{{ vueErrorsList.first('category_id') }}</span>
</div>
</div>
</div>
</form>
</section>
</template>
<script>
import {bus} from '../../app';
...
import vSelect from 'vue-select'
Vue.component('v-select', vSelect) // https://github.com/sagalbot/vue-select
import moment from 'moment';
...
export default {
created() {
this.$validator.localize(window.CURRENT_LANG, {
attributes: {
selection_category_id: 'category',
category_id: 'category',
...
}
});
}, // created() {
...
methods
:
{
validateBeforeSubmit()
{
this.$validator.validateAll().then((result) => {
if (result) {
this.updateTask()
} else {
this.showPopupMessage('Error ' + ( this.is_insert ? 'adding' : 'updating' ) + ' task. ', 'error');
}
})
}
, // validateBeforeSubmit() {
updateTask()
{
...
}
, // updateTask() {
} // methods:{
}
</script>
But In the code above the second input is vue-select element ( https://github.com/sagalbot/vue-select )
and it is not validated at all.
I put
v-validate="'required'"
to it but it does not work.
I use validateBeforeSubmit method and if there is a way to make some kind of custom validation, so I would check is value in
select input is selected?
Thank you!

Vuejs components not getting displayed

I've a password_reset.vue script as below:
<template>
<form>
<div class="alert alert-danger" v-if="form.errors.has('photo')">
#{{ form.errors.get('photo') }}
</div>
<div class="row">
<div class="col-md-3">
<div class="label">Current Password</div>
</div>
<div class="col-md-9">
<div class="field--wrapper">
<label for="current_password">Current Password</label>
<input class="nom-fields" type="password"
v-model="form.current_password"
id="current_password" name="current_password"
placeholder="Current Password" value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="label">Repeat Password</div>
</div>
<div class="col-md-9">
<div class="field--wrapper">
<label for="password_repeat">Repeat Password</label>
<input class="nom-fields" type="password"
v-model="form.password_repeat"
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-9 text-right">
<button id="change_password"
class="blue-btn" v-on:click="update">
Change Password
</button>
</div>
</div>
</form>
</template>
<script>
export default{
data(){
return{
form: new MyForm({
current_password: '',
new_password: '',
password_repeat: '',
message: ''
})
};
},
methods: {
/**
* Update the user's password.
*/
update(e) {
e.preventDefault();
this.form.startProcessing();
this.$http.post('/account/change_password', this.form)
.then(function(response) {
this.form.finishProcessing();
})
.catch(function(response) {
this.form.setErrors(response.data);
});
},
}
}
</script>
and in my bootstrap.js file, I've:
import './interceptors.js';
import './forms/form.js';
import './forms/errors.js';
import PasswordReset from './settings/password_reset.vue'
new Vue({
el: 'body',
components: {
PasswordReset
},
ready() {
}
});
and in the app.js file I've:
import './bootstrap.js'
HTML:
<body>
<password-reset></password-reset>
</body>
But it seems the component is not getting displayed. I tried to alert a msg in the ready method and it's working fine. I'm loading Vue.js also.

Resources