two select dynamics vue laravel - 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?

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

Laravel Vue store data foreign key

<form #submit.prevent="store">
<div class="form-group mb-3">
<label class="form-label">NIP</label>
<input type="text" class="form-control" v-model="pegawai.nomor_induk_pegawai"
placeholder="Masukkan nomor induk pegawai">
<!-- validation -->
<div v-if="validation.nomor_induk_pegawai" class="mt-2 alert alert-danger">
{{ validation.nomor_induk_pegawai[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Nama Pegawai</label>
<input class="form-control" v-model="pegawai.nama_pegawai"
placeholder="Masukkan nama pegawai">
<!-- validation -->
<div v-if="validation.nama_pegawai" class="mt-2 alert alert-danger">
{{ validation.nama_pegawai[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Departemen</label>
<select class="form-control" v-model="pegawai.id_departemen">
<option v-for="departemen in departemens" v-bind:value="departemen.id">{{ departemen.nama_departemen }}</option>
</select>
<div v-if="validation.id_departemen" class="mt-2 alert alert-danger">
{{ validation.id_departemen[0] }}
</div>
</div>
<div class="form-group mb-3">
<label class="form-label">Email</label>
<input type="text" class="form-control" v-model="pegawai.email"
placeholder="Masukkan email">
<!-- validation -->
<div v-if="validation.email" class="mt-2 alert alert-danger">
{{ validation.email[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Telepon</label>
<input class="form-control" v-model="pegawai.telepon" placeholder="Masukkan telepon">
<!-- validation -->
<div v-if="validation.telepon" class="mt-2 alert alert-danger">
{{ validation.telepon[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Gender</label>
<select class="form-control" v-model="pegawai.gender">
<option value="0"> Wanita </option>
<option value="1"> Pria </option>
</select>
<!-- validation -->
<div v-if="validation.gender" class="mt-2 alert alert-danger">
{{ validation.gender[0] }}
</div>
</div>
<div class="form-group mb-3">
<label for="content" class="form-label">Status</label>
<select class="form-control" v-model="pegawai.status">
<option value="1"> Aktif </option>
<option value="0"> Tidak Aktif </option>
</select>
<!-- validation -->
<div v-if="validation.status" class="mt-2 alert alert-danger">
{{ validation.status[0] }}
</div>
</div>
<button type="submit" class="btn btn-primary">SIMPAN</button>
<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
export default {
setup() {
//state departemen
const pegawai = reactive({
nomor_induk_pegawai: '',
id_departemen:'',
nama_pegawai: '',
email: '',
telepon: '',
gender: '',
status: ''
})
let departemens = ref([])
onMounted(() => {
//get API from Laravel Backend
axios.get('http://localhost:8000/api/departemens')
.then(response => {
//assign state posts with response data
departemens.value = response.data.data
}).catch(error => {
console.log(error.response.data)
})
})
//state validation
const validation = ref([])
//vue router
const router = useRouter()
//method store
function store() {
let nomor_induk_pegawai = pegawai.nomor_induk_pegawai
let nama_pegawai = pegawai.nama_pegawai
let id_departemen = departemen.id
let email = pegawai.email
let telepon = pegawai.telepon
let gender = pegawai.gender
let status = pegawai.status
axios.post('http://localhost:8000/api/pegawais', {
nomor_induk_pegawai: nomor_induk_pegawai,
nama_pegawai: nama_pegawai,
id_departemen: id_departemen,
email: email,
telepon: telepon,
gender: gender,
status: status
}).then(() => {
//redirect ke post index
router.push({
name: 'pegawai.index'
})
}).catch(error => {
//assign state validation with error
validation.value = error.response.data
})
}
//return
return {
departemens,
pegawai,
validation,
router,
store
}
}
I'm trying to create data in table pegawais with id_departemen as foreign key from table departemens. the dropdown on label departemen suppose to show nama_departemen from table departemen with value id from table department. So I tried this and it said
32:37 error Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key
128:33 error 'departemen' is not defined no-undef
As written in the error, this is how you should have it
<option v-for="departemen in departments"
:value="departemen.id"
:key="departmen.id" // 👈🏻 missing that one
>
{{ departemen.nama_departemen }}
</option>
More details are available here: https://eslint.vuejs.org/rules/require-v-for-key.html
And also here: https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
TLDR: when using a v-for, add a :key to it.

POST http://127.0.0.1:8000/ 422 (Unprocessable Content)

I have an error on login form after upgrading version Vue JS, Axios, Laravel.
This project code working well with old version. Anyone can explain this serious errors.
Thanks you for your help!
And I stuck with it many days. I've search for similar post error, but only seen this(POST http://127.0.0.1:8000/ 422 (Unprocessable Entity)).
<template>
<div class="back-img" :style="`background-image: url('${appUrl}/images/background/default-background.jpg')`">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-md-6 offset-md-6 col-lg-4 offset-lg-8 col-xl-4 offset-xl-8 pl-0">
<div class="sign-in-sign-up-content">
<form class="sign-in-sign-up-form">
<div class="text-center mb-4 application-logo">
<img :src="publicPath+'/uploads/logo/'+appLogo" alt="" class="img-fluid logo">
</div>
<div class="form-row">
<div class="form-group col-12">
<h3 class="text-center mb-0">
{{ trans('lang.hi_there') }}
</h3><br>
<label class="text-center d-block">
{{ trans('lang.sign_in_to_your_dashboard') }}
</label>
</div>
</div>
<div v-if="alertMessage.length>0" class="alertBranch">
<div class="alert alert-warning alertBranch" role="alert">
{{alertMessage}}
</div>
</div><br>
<div class="form-row">
<div class="form-group col-12">
<label for="username" style="font-size: 20px;"> {{ trans('lang.login_username') }}</label>
<input id="username"
v-validate="'required'"
v-model="username"
type="text"
name="username"
class="form-control"
:placeholder="trans('lang.enter_username')"
:class="{ 'is-invalid': submitted && errors.has('username') }">
<div class="heightError" v-if="submitted && errors.has('username')">
<small class="text-danger" v-show="errors.has('username')">
{{ errors.first('username') }}
</small>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label for="password" style="font-size: 20px !important;">{{ trans('lang.login_password') }}</label>
<input id="password"
v-validate="'required'"
ref="password"
v-model="password"
name="password"
type="password"
class="form-control"
:placeholder="trans('lang.enter_password')"
:class="{ 'is-invalid': submitted && errors.has('password') }">
<div class="heightError">
<small class="text-danger" v-show="errors.has('password')">
{{ errors.first('password') }}
</small>
</div>
</div>
</div>
<div class="form-row loginButton">
<div class="form-group col-12">
<common-submit-button class="btn-block text-center auth-button"
style="font-size: 20px !important;"
:buttonLoader="buttonLoader"
:isDisabled="isDisabled"
:isActiveText="isActiveText"
buttonText="login"
v-on:submit="loginPost"/>
</div>
</div>
<!-- <div class="form-row">
<div class="form-group col-12">
<a href="#"
#click="forgetPassword"
class="bluish-text">
<i class="fa fa-lock"/>
{{ trans('lang.forgot_password') }}
</a>
</div>
</div> -->
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axiosGetPost from '../../helper/axiosGetPostCommon';
export default {
extends: axiosGetPost,
props: ['checkusername', 'checkpass'],
data() {
return {
username: this.checkusername,
name: '',
password: this.checkpass,
remember: true,
buttonLoader: false,
isActiveText: false,
isDisabled: false,
preLoaderType: 'load',
hidePreLoader: false,
isActive: 'active',
alertMessage: '',
submitted: false,
}
},
methods: {
loginPost() {
this.submitted = true,
this.$validator.validateAll().then((result) => {
if (result) {
this.inputFields = {
username: this.username,
password: this.password,
};
this.buttonLoader = true;
this.isDisabled = true;
this.isActiveText = true;
this.loginPostMethod('/', {
username: this.username,
password: this.password,
}
);
}
});
},
forgetPassword() {
let instance = this;
instance.redirect('/password/reset');
},
loginPostSucces(response) {
let instance = this;
instance.redirect("/sales");
},
loginPostError(response) {
let instance = this;
instance.buttonLoader = false;
instance.isDisabled = false;
instance.isActiveText = false;
instance.alertMessage = response.data.errors.username[0];
},
}
}
</script>
File: resources\assets\js\js\bootstrap.js
window._ = require('lodash');
window.Popper = require('popper.js').default;
import axios from "axios";
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
if (document.querySelector('meta[name="csrf-token"]')) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
}
You have to pass the csrf token in Ajax request.
data: {
"_token": "{{ csrf_token() }}",
other form data
}
OR
You can create csrf token in header using meta element and access that value in while sending ajax request.
<meta name="csrf-token" content="{{ csrf_token() }}" />
// Access in ajax request like below
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
Laravel + Vue + Axios
Laravel has configurd the default token header in resources/js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
So you have to just import axios like.
import axios from 'axios';

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

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