I have a problem passing the selected option value id from select option to onchange function in methods. What i want to achieve here everytime i change select value in select option i would like to store the selected value to v-model=choosed and pass that value to methods onchange that choosed = item.id.
Here is my function in DeviceController to fetch devices:
public function devices()
{
try {
$devices = Device::orderby('id', 'asc')->get();
return response()->json($devices);
} catch (\Throwable $th) {
return response()->json(['message' => $th->getMessage()]);
}
}
Here is the function from method to get devices{} data from DeviceController:
getDevices() {
axios.get(`/api/devices`)
.then(response => {
this.devices = response.data;
});
},
Here is my select option code:
<select v-model="choosed" @change="onChange()">
<option :value="null">Choose Device to Send SMS</option>
<option v-for="item in devices" :key="item.id" :value="item.id" >{{ item.device_name }}
</option>
</select>
Here is my choosed v-model and devices json which devices that item.id came from in data:
export default {
data() {
return {
devices: {},
choosed: null,
}
},
Here is my onChange function in method:
onChange: function(){
this.choosed = this.item.id;
},
CodePudding user response:
Try this... https://codesandbox.io/s/vue-2-playground-forked-8yeqkx?file=/src/App.vue
<template>
<div id="app">
<select
v-model="choosed"
>
<option :value="null">Choose Device to Send SMS</option>
<option v-for="item in devices" :key="item.id" :value="item.id">
{{ item.device_name }}
</option>
</select>
<p>Selected id: {{ choosed }}</p>
</div>
</template>
<script>
const devices = async () => {
await new Promise((r) => setTimeout(r, 2000));
return [
{
id: 0,
device_name: "Device A",
},
{
id: 1,
device_name: "Device B",
},
{
id: 2,
device_name: "Device C",
},
];
};
export default {
name: "App",
data() {
return {
choosed: null,
devices: [],
};
},
async mounted() {
this.$set(this, "devices", await devices());
},
};
</script>
CodePudding user response:
Try this.
<template>
<div id="app">
<select
@change="onChange($event)"
>
<option :value="null">Choose Device to Send SMS</option>
<option v-for="item in devices" :key="item.id" :value="item.id">
{{ item.device_name }}
</option>
</select>
<p>Selected id: {{ choosed }}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
choosed: null,
devices: [
{
id: 1,
device_name: 'iphone'
},
{
id: 2,
device_name: 'android'
}
],
};
},
methods: {
onChange: function (event) {
this.choosed = event.target.value
}
}
};
</script>