Dynamic select box data binding on vuejs - laravel

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}`"

Related

select options based on another select VueJS Laravel

I am using VueJs with laravel, I am new in VueJs and i want to display the Categories dynamically whenever i choose any Collection, i am sending API and using Axios, but i cant seem to figure out how to make this work.
Any help will be highly appreciated
<div class="form-group">
<label for="">Collection</label>
<select
class="form-control"
v-model="collection"
#change="getCategory()"
>
<option
v-for="datas in data"
:key="datas.collection_name"
:value="datas.collection_id"
>
{{ datas.collection_name }}
</option>
</select>
</div>
<div class="form-group">
<label for="">Category</label>
<select class="form-control" v-model="category">
<option :value="category">
{{ category_name }}
</option>
</select>
</div>
data() {
return {
category_name: "",
collection: null,
category: null,
};
},
methods: {
getCategory() {
console.log(this.collection);
axios
.get("/api/products")
.then((response) => {
console.log(response.data[0].category_id);
this.category = response.data[0].category_id;
this.category_name = response.data[0].category_id;
})
.catch((err) => {
console.log(err);
});
},
Controller:
public function create(){
$collection = Collection::join('categories','collections.id','=','categories.collection_id')
->select('categories.name as category_name','categories.id as category_id','collections.name as collection_name','collections.id as collection_id')
->get();
return response()->json($collection);
}
Axios response.data output is :
if I got your question very well. You want to dynamically display your categories after choosing collection data that are in laravel backend API.
in your script in vue js
data(){
return {
form: {
collection:'',category: '' //define your v-models here
},
categories:{},
errors: [],
}
},
method:{
getCategories(){
axios.get('/categories/' + this.form.collection).then(response => {
this.categories = response.data
}).catch(errors => {
this.errors = error.response.data.errors
})
},
},
in your template now (html)
<div class="col-lg-6">
<div class="mb-3">
<label class="form-label">collection</label>
<select v-model="form.collection" class="form-control" #change="getCategories()">
<option value="">Select Collection</option>
<option :value="collection.id" v-for="collection in collections" :key="country.id">{{ country.name }}</option>
</select>
<div v-if="errors.collection" class="text-small text-danger"> {{ errors.collection[0] }}</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Category</label>
<div class="form-icon position-relative">
<select class="form-control" v-model="form.category">
<option value="">Select Category</option>
<option :value="category.id" v-for=" categories" :key="city.id">{{ category.name }}</option>
</select>
<div v-if="errors.category" class="text-small text-danger">{{ errors.city_id[0] }}</div>
</div>
</div>
</div>
you better define your v-models with form as I did above it will help you not confusing yourself. example form.collection
This should work.
<template>
<div>
<div class="form-group">
<label for="">Collection</label>
<select
class="form-control"
v-model="collection"
#change="getCategory()"
>
<option
v-for="datas in data"
:key="datas.collection_name"
:value="datas.collection_id"
>
{{ datas.collection_name }}
</option>
</select>
</div>
<div class="form-group">
<label for="">Category</label>
<select class="form-control" v-model="category" v-if="category_list.length > 0">
<option v-for="(category, index) in category_list" :key="index" :value="category.id">
{{ category.category_name }}
</option>
</select>
</div>
</div>
</template>
<script>
export default{
data() {
return {
category: null,
category_list: null
};
},
methods: {
getCategory() {
axios
.get("/api/products")
.then((response) => {
this.category_list = response.data;
})
.catch((err) => {
console.log(err);
});
},
}
</script>

How to update more table rows at once using Laravel and Vuejs?

I have settings table with 3 columns (id, property, content).
I have seeded some data into settings table and I want to update this table. I am filling some form where each input is presenting one row of the table settings. After submitting that form, I want my table to be updated...
For example, some of my property-content pairs (some of my inputs in this form) are:
background_image - 'image.jpg'
header - 'this is the header'
I am confused because I don't really know what should I send to backend and also I am not sure what should endpoint be...
I hope some of you can help me. If you need more questions, be free to ask me. Thanks in advance, and here is my code:
SettingsController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Requests\UpdateSettings;
use App\Http\Resources\SettingResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
class SettingController extends Controller
{
public function index()
{
$settings = Setting::all();
return SettingResource::collection($settings);
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function update(UpdateSettings $request, Setting $setting)
{
$setting->where('property', $request->property)
->update([ 'content' => $request->content ]);
return new SettingResource($setting);
}
public function destroy($id)
{
//
}
}
Settings.vue
<template>
<div class="ml-4 container">
<button #click="submit" id="saveBtn" class="btn btn-primary mt-2">Save Admin Settings</button>
<div class="custom-file mt-3">
<label for="backgroundImage" class="custom-file-label input">Add Background Image</label>
<input id="backgroundImage" #input="errors.clear('background_image')" #change="uploadImageName" type="file" class="custom-file-input btn btn-primary"
style="background: #1d68a7">
<span class="text-danger" v-if="errors.get('background_image')">{{ errors.get('background_image') }}</span>
</div>
<div class="form-group mt-3">
<label for="header">Header</label>
<input :class="{'is-invalid' : errors.get('header')}" #input="errors.clear('header')" v-model="form.header" type="text" class="form-control input" id="header">
<span class="text-danger" v-if="errors.get('header')">{{ errors.get('header') }}</span>
</div>
<div class="form-group mt-3">
<label for="videoOne">Video one</label>
<textarea :class="{'is-invalid' : errors.get('video')}" #input="errors.clear('video')" v-model="form.video" type="text" class="form-control videoBox input" id="videoOne"></textarea>
<span class="text-danger" v-if="errors.get('video')">{{ errors.get('video') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_video"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionOneText">Section One Text</label>
<editor
#input="errors.clear('section_one')"
v-model="form.section_one"
type="text"
class="form-control"
id="sectionOneText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_one')">{{ errors.get('section_one') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_one"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="editableBoxContainer">Editable Box Container</label>
<editor
#input="errors.clear('editable_box')"
v-model="form.editable_box"
type="text"
class="form-control"
id="editableBoxContainer"
>
</editor>
<span class="text-danger" v-if="errors.get('editable_box')">{{ errors.get('editable_box') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_editable_box"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionTwoText">Section Two Text</label>
<editor
#input="errors.clear('section_two')"
v-model="form.section_two"
type="text"
class="form-control"
id="sectionTwoText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_two')">{{ errors.get('section_two') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_two"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionThreeText">Section Three Text</label>
<editor
#input="errors.clear('section_three')"
v-model="form.section_three"
type="text"
class="form-control"
id="sectionThreeText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_three')">{{ errors.get('section_three') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_three"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="form-group mt-3">
<label for="videoTwo">Video two</label>
<textarea :class="{'is-invalid' : errors.get('video_two')}" #input="errors.clear('video_two')" v-model="form.video_two" type="text" class="form-control videoBox input" id="videoTwo"></textarea>
<span class="text-danger" v-if="errors.get('video_two')">{{ errors.get('video_two') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_video_two"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="form-group mt-3">
<label for="linkOne">Link One</label>
<input :class="{'is-invalid' : errors.get('link_one')}" #input="errors.clear('link_one')" v-model="form.link_one" type="text" class="form-control input" id="linkOne">
<span class="text-danger" v-if="errors.get('link_one')">{{ errors.get('link_one') }}</span>
</div>
<div class="form-group mt-3">
<label for="linkTwo">Link Two</label>
<input :class="{'is-invalid' : errors.get('link_two')}" #input="errors.clear('link_two')" v-model="form.link_two" type="text" class="form-control input" id="linkTwo">
<span class="text-danger" v-if="errors.get('link_two')">{{ errors.get('link_two') }}</span>
</div>
</div>
</template>
<script>
import Editor from '#tinymce/tinymce-vue'
import {ToggleButton} from 'vue-js-toggle-button'
import Errors from "../helpers/Errors";
Vue.component('ToggleButton', ToggleButton)
export default {
name: "Settings",
components: {Editor},
data() {
return {
errors: new Errors(),
form: {
background_image: '',
header: '',
video: '',
active_video: null,
section_one: '',
active_section_one: null,
editable_box: '',
active_editable_box: null,
section_two: '',
active_section_two: null,
section_three: '',
active_section_three: null,
video_two: '',
active_video_two: null,
link_one: '',
link_two: '',
},
}
},
mounted() {
},
methods: {
toggleBtn() {
if (this.sectionTwotext) {
this.sectionTwotext = false;
} else {
this.sectionTwotext = true;
}
},
async submit() {
try {
const form = Object.assign({}, this.form);
console.log(form);
let result = Object.keys(form).map(function (key) {
return [key, form[key]];
});
console.log(result[0])
result._method = 'PUT';
for(let i=0; i<=15; i++) {
let objectResult = Object.assign({}, result[i]);
console.log('objectResult')
console.log(objectResult)
objectResult._method = 'PUT';
const {data} = await axios.post(`/api/setting/${i}`, objectResult);
}
} catch (error) {
console.log(error.response.data.errors);
this.errors.record(error.response.data.errors);
}
},
uploadImageName() {
let image = document.getElementById("backgroundImage");
this.form.background_image = image.files[0].name;
console.log(image.files[0].name);
},
}
}
</script>
<style scoped>
#saveBtn {
border-radius: 0;
}
.input {
border-radius: 0;
}
.videoBox {
height: 300px;
}
.toggleButton {
margin-left: auto;
}
</style>
My async Submit function is not OK, I was just trying something...
Thanks in advance!
I would consider having a single endpoint on your api where you submit the entire form.
api.php
Create a route that we can submit our axios request to:
Route::put('/settings', 'Api\SettingController#update')->name('api.settings.update');
Note that I have namespaced the controller as you will likely have a web and api version of this controller. Mixing your api and web actions in a single controller is not advisable.
web.php
This is a standard web route which will display a blade view containing the vue component. We pass through the settings which will then be passed to the Settings.vue component as a prop.
Route::get('/settings', 'SettingController#edit')->name('settings.edit');
edit.blade.php
<settings :settings="{{ $settings }}"></settings>
Settings.vue
axios.put('/api/settings', {
header: this.form.header,
background_image: this.form.background_image
... other fields to be submitted
})
.then(success => {
console.log(success);
})
.catch(error => {
console.log(error);
});
SettingController.php
public function edit()
{
return view('settings.edit', ['settings' => Setting::all()]);
}
Api\SettingController.php
public function update(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'header' => ['required', 'string'],
'background_image' => ['required', 'string']
... other fields to be validated
]
);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 422);
}
foreach ($validator->validated() as $property => $content) {
Setting::where('property', $property)->update(['content' => $content]);
}
return response()->json(['success' => true], 200);
}
You might want to consider splitting settings into groups and submitting groups rather than the entire form, or submitting each setting individually (where it makes sense to do so).

two select dynamics vue laravel

I want to load 2 select with vue, I have country, city state, but I don't want to call the js from resources / app.js since I don't need it in all the pages only in a particular sight. I am new to vue. when I load it from resources / app.js if it works but only for status but not for city and in the other pages it throws me an error since it cannot find the object.
I don't want to call him here
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
//require('./estado');
//require('./ciudad');
so how do i make the call and where do i put the js files
file get state resources/js/estado.js
const app = new Vue({
el: '#app',
data: {
selected_pais: '',
selected_estado: '',
selected_ciudad: '',
estados: [],
ciudades: [],
},
mounted(){
document.getElementById('estado').disabled = true;
this.selected_pais = document.getElementById('pais').getAttribute('data-old');
if(this.selected_pais !='')
{
this.loadEstados();
}
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad = document.getElementById('ciudad').getAttribute('data-old');
},
methods: {
loadEstados() {
this.selected_estado ='';
document.getElementById('estado').disabled =true;
if (this.selected_pais !="") {
axios.get(`http://127.0.0.1:80/estados/pais`, {params: {pais_id: this.selected_pais} }).then((response) => {
this.estados = response.data;
document.getElementById('estado').disabled =false;
});
}
},
cargarCiudades() {
this.selected_ciudad ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
},
}
});
file get city resources/js/ciudades.js
const app = new Vue({
el: '#app',
data: {
selected_estado: '',
selected_ciudad: '',
ciudades: [],
},
mounted(){
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad2 = document.getElementById('ciudad').getAttribute('data-old');
},
method: {
cargarCiudades() {
this.selected_ciudad2 ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
}
}
});
files view
#extends('layouts.app')
#section('content')
#inject('paises','App\Services\Paises')
<div class="container">
<div class="row">
<div class="col-md-8">
#if ($errors->any())
<div class="alert alert-danger">
<h4>Por Favor corriga los siguientes errores </h4>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/usuarios" method="POST">
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Nombre</label>
<input type="text" class="form-control" name="nombre" id="inputEmail4" placeholder="Nombre" value="{{old('nombre')}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="text" class="form-control" name="email" id="inputPassword4" placeholder="Email" value="{{old('email')}}">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Direccion</label>
<input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St" name="direccion" value="{{old('direccion')}}">
</div>
<div class="form-row">
<div class="form-group col-md-4" id="div_pais">
<label for="inputCity">Pais</label>
<select v-model="selected_pais" id="pais" data-old="{{old('cbo_pais')}}"
v-on:change="loadEstados()" name="cbo_pais" class="form-control">
#foreach ($paises->get() as $index => $pais)
<option value="{{$index}}" >{{$pais}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Estado</label>
<select v-model="selected_estado" id="estado" data-old="{{old('cbo_estado')}}"
v-on:change="cargarCiudades()" name="cbo_estado" class="form-control" >
<option value="">Selecione un Estado</option>
<option v-for="(estado, index) in estados" v-bind:value="index">#{{estado}}</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState">Ciudad</label>
<select v-model="selected_ciudad" id="ciudad" data-old="{{old('cbo_ciudad')}}"
name="cbo_ciudad" class="form-control" >
<option value="">Selecione un Ciudad</option>
<option v-for="(ciudad, index) in ciudades" v-bind:value="index">#{{ciudad}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputZip">Zip</label>
<input type="text" class="form-control" id="inputZip" name="zip">
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Registrar</button>
<button type="reset" class="btn btn-danger">Cancelar</button>
</form>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
how do I call the files in the view?

Select2 form input not change value with vue

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">

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>

Resources