My component vue.js is like this :
<script>
export default{
name: 'CategoryBsSelect',
template: '\
<select class="form-control" v-model="selected" required>\
<option v-for="option in options" v-bind:value="option.id" v-bind:disabled="option.disabled">{{ option.name }}</option>\
</select>',
//props: {list: {type: String, default: ''}},
mounted() {
this.fetchList();
},
data() {
return {
selected: '',
options: [{id: '', name: 'Pilih Kategori'}]
};
},
methods: {
fetchList: function() {
this.$http.post(window.BaseUrl+'/member/category/list').then(function (response) {
//this.$set('list', response.data);
console.log(JSON.stringify(response.body))
Object.keys(response.body).forEach(function (key) {
console.log(key)
console.log(response.body[key])
this.$set(this.options, key, response.body[key]);
}, this);
});
},
}
};
</script>
The result of console.log(JSON.stringify(response.body)) :
{"20":"Category 1","21":"Category 2","22":"Category 3"}
I want display the response on the value of select. But when executed, on the console exist error like this :
TypeError: Cannot read property 'id' of undefined
Is there anyone who can help me?
The issue you are having is the final this.options variable is an hash nat an array, which should be an input to select element, you can modify you code inside fetchList method like following:
Object.keys(resp).forEach((key) => {
console.log(key)
console.log(resp[key])
this.options.push({
id: key,
name: resp[key]
})
});
Have a look at working fiddle here.
Related
How do you guys get the text inside a p tag and store it in a variable in VueJS?
Because right now, it just displays it in a p tag but I want the text inside the p tag to be stored in a variable for later use.
Below is my html code
<b-form-input v-model="search" placeholder="Search by disease"></b-form-input>
<select v-model="selected">
<option v-for="result in filteredPeople(search)" :key="result.LONG_D" :value="{ id: result.LONG_D, text: result.ICD_C }">{{ result.LONG_D }}</option>
</select>
<p>
Value: {{selected.id}}
</p>
<b-button class="btn" variant="success" v-on:click="runAPI(search)">Search</b-button>
And this one is my JS code.
export default {
data() {
return {
results: {},
search: "",
msg: null,
selected: ""
};
},
methods: {
runAPI: function(disease) {
axios
.get("http://localhost:9000/api/disease/" + disease)
.then(response => (this.results = response.data))
.catch(error => console.log(error));
console.log(this.results);
},
filteredPeople() {
if (this.searchQuery) {
return this.results.filter(item => {
return item.LONG_D.startsWith(this.searchQuery);
});
} else {
return this.results;
}
}
}
One way would be to put a function in the tag that takes the value (it could also of course return the value so the display wouldn't change). The function could then store the value in a data or local variable and you would have it.
like so:
{{getSelectedId(selected.id)}}
anything inside {{}} is JS so you can have functions and even use logic (although not so recommended to put too much logic in template).
You can do like this .
JS CODE
export default {
data() {
return {
results: {},
search: "",
msg: null,
selected: ""
};
},
methods: {
runAPI: function(disease) {
axios
.get("http://localhost:9000/api/disease/" + disease)
.then(response => (this.results = this.filteredPeople()))
.catch(error => console.log(error));
console.log(this.results);
},
filteredPeople() {
if (this.searchQuery) {
return this.results.filter(item => {
return item.LONG_D.startsWith(this.searchQuery);
});
} else {
return this.results;
}
HTML CODE
<select v-model="selected">
<option
v-for="result in results"
:key="result.LONG_D"
:value="{{ id: result.LONG_D, text: result.ICD_C }}">{{ result.LONG_D }}</option>
</select>
I am calling service in Angular7 at every dropdown option change. But when I change selected option on dropdown I am getting getAllByCountryId of undefined error.
Here is function that calling http service:
countryOnChange(countryId: Guid) {
this.cityService.getAllByCountryId(countryId).subscribe(
res => {
if (res.code === ResponseCode.success) {
res.dataList.map(item => {
this.cities.push({
value: item.id.toString(),
label: item.dataValue
});
});
if (this.formComponent !== undefined) {
this.formComponent.form.controls['cityId'].patchValue(this.cities);
}
}
},
err => {
this.error = true;
});
}
Here is the HTML code that calling above function on every dropdown option change:
<ng-container *ngSwitchCase="'dropdown'" class="col-md-12">
<ng-select [ngClass]="'ng-select'" [options]="input.options" [formControlName]="input.key" [id]="input.key" (selected)="input.onChange($event.value)"></ng-select>
</ng-container>
input.onChange($event.value) and countryOnChange is connected at the backend.
Here is how to call countryOnChange function:
const dropdown2 = new InputDropdown({
key: 'countryId',
label: '',
onChange: this.countryOnChange,
options: this.countries,
value: '',
required: true,
order: 3
});
Error http://prntscr.com/ovjxe7
How can I solve this problem?
I think [ngModel] is needed:
<select [ngModel]="selectedValue" (ngModelChange)="onDropdownChange($event)"
class="form-control">
<option *ngFor="let category of categorylist" [ngValue]="category.id">
{{category.Description}}</option>
</select>
refer to: Angular 2 How to bind selected id in Dropdownlist with model?
getAllByCountryId of undefined error means you are getting this.cityService as undefined.
Check with which this context your function is binding when you are creating the InputDropDown. May be you need to define it like :-
const dropdown2 = new InputDropdown({
key: 'countryId',
label: '',
onChange: this.countryOnChange.bind(this),
options: this.countries.bind(this),
value: '',
required: true,
order: 3
});
Hope this helps.
I am new to VueJS, and i am using Vuejs-Multiselect, enabling the multiple option.
I need to pass the selected value to the toggleSelected method .
In this pen, there is a simulation : https://codepen.io/amrigo/pen/arvadE
I see the values are concatenated, eg.: when i choose the first value i can see using console.log : [object Object], choosing the second [object Object],[object Object] and so on.
How can i get just the selected value and so the code value from the options array?
In the html i do use :
<div id="app">
<multiselect
v-model="value"
:options="options"
:multiple="true"
track-by="name"
:hide-selected="true"
:close-on-select="false"
:custom-label="customLabel"
:searchable="false"
placeholder=""
:show-labels="false"
#input="toggleSelected(value)"
>
</multiselect>
<pre>{{ value }}</pre>
</div>
In the script i do use :
new Vue({
components: {
Multiselect: VueMultiselect.default
},
data: {
value: [],
options: [
{ name: 'Agriculture', code: '1' },
{ name: 'Police', code: '2' },
{ name: 'Medical', code: '3' }
]
},
methods: {
customLabel (option) {
return `${option.name}`
},
toggleSelected(value) {
alert( `${value.name}` )
console.log(' >> '+ `${value}` )
}
}
}).$mount('#app')
From the documentation, to get the selected option you use the #select event.
Example:
<multiselect
// ... all your props*
#select="optionSelected">
</multiselect>
// dont put the brackets (),
//js will automatically pass the values to toggleSelected
//In your method:
optionSelected(option, id) {
console.log(option)
}
You can use a computed property for that. Do something like this:
computed: {
valueIds() {
return this.value.map(v => v.id);
}
}
See this working example:
https://jsfiddle.net/ebbishop/7eku4vf0/
I am working with vue and here is my code
everything is working fine until I submitting the form. when I submit form and try to update emailForm -> tabs -> en -> data -> name then i got an error.
<template>
<el-form :model="emailForm.tabs" ref="emailForm" class="demo-emailForm" #submit="submitForm('emailForm')">
<div v-for="(lan, key, index) in emailForm.tabs">
<el-form-item :label="$t('Template Name')" >
{{lan.data.name}}
</el-form-item>
<el-form>
<template>
<script>
export default {
data() {
return {
emailForm: {
tabs: {
en: {
sortHeand: 'en',
title: 'English',
data: {
name: "ad",
subject: "asda",
html_code: 'asdad',
status: 0
}
}
}
}
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
request({
url: this.getRoute(),
method: "post",
data: this[formName].tabs
})
.then(response => {
console.log(response)
})
}
});
},
}
}
</script>
Anyone can render this issue ?
You're trying to read property name from variable/object data but data is undefined so it can't read the property name from it.
I'm building a key-command resource and giving VueJS a whirl while doing so. I'm a newbie but am gaining the grasp of things (slowly...).
I want to be able to search in a global search form for key commands I'm defining as actions within sections of commands (see data example below). I would like to search through all the actions to show only those that match the search criteria.
My HTML is below:
<div id="commands">
<input v-model="searchQuery" />
<div class="commands-section" v-for="item in sectionsSearched"
:key="item.id">
<h3>{{ item.section }}</h3>
<div class="commands-row" v-for="command in item.command" :key="command.action">
{{ command.action }}
</div>
</div>
</div>
My main Vue instance looks like this:
import Vue from 'vue/dist/vue.esm'
import { commands } from './data.js'
document.addEventListener('DOMContentLoaded', () => {
const element = document.getElementById("commands")
if (element != null) {
const app = new Vue({
el: element,
data: {
searchQuery: '',
commands: commands
},
computed: {
sectionsSearched() {
var self = this;
return this.commands.filter((c) => {
return c.command.filter((item) => {
console.log(item.action)
return item.action.indexOf(self.searchQuery) > -1;
});
});
},
}
});
}
});
And finally the data structure in data.js
const commands = [
{
section: "first section",
command: [
{ action: '1' },
{ action: '2' },
{ action: '3' },
],
},
{
section: "second section",
command: [
{ action: 'A' },
{ action: 'B' },
{ action: 'C' },
]
},
]
export { commands };
I'm able to output the commands using the console.log(item.action) snippet you see in the computed method called sectionsSearched.
I see no errors in the browser and the data renders correctly.
I cannot however filter by searching in real-time. I'm nearly positive it's a combination of my data structure + the computed method. Can anyone shed some insight as to what I'm doing wrong here?
I'd ideally like to keep the data as is because it's important to be sectioned off.
I'm a Rails guy who is new to this stuff so any and all feedback is welcome.
Thanks!
EDIT
I've tried the proposed solutions below but keep getting undefined in any query I pass. The functionality seems to work in most cases for something like this:
sectionsSearched() {
return this.commands.filter((c) => {
return c.command.filter((item) => {
return item.action.indexOf(this.searchQuery) > -1;
}).length > 0;
});
},
But alas nothing actually comes back. I'm scratching my head hard.
There is a issue in your sectionsSearched as it is returning the array of just commands.
See this one
sectionsSearched() {
return this.commands.reduce((r, e) => {
const command = e.command.filter(item => item.action.indexOf(this.searchQuery) > -1);
const section = e.section;
r.push({
section,
command
});
}, []);
}
const commands = [
{
section: "first section",
command: [
{ action: '1' },
{ action: '2' },
{ action: '3' },
],
},
{
section: "second section",
command: [
{ action: 'A' },
{ action: 'B' },
{ action: 'C' },
]
},
]
const element = document.getElementById("commands")
if (element != null) {
const app = new Vue({
el: element,
data: {
searchQuery: '',
commands: commands
},
computed: {
sectionsSearched() {
var self = this;
return this.commands.filter((c) => {
// the code below return an array, not a boolean
// make this.commands.filter() not work
// return c.command.filter((item) => {
// return item.action.indexOf(self.searchQuery) > -1;
// });
// to find whether there has command action equal to searchQuery
return c.command.find(item => item.action === self.searchQuery);
});
},
}
});
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="commands">
<input v-model="searchQuery" />
<div class="commands-section" v-for="item in sectionsSearched"
:key="item.id">
<h3>{{ item.section }}</h3>
<div class="commands-row" v-for="command in item.command" :key="command.action">
{{ command.action }}
</div>
</div>
</div>
Is that work as you wish ?
sectionsSearched() {
return this.commands.filter((c) => {
return c.command.filter((item) => {
return item.action.indexOf(this.searchQuery) > -1;
}).length > 0;
});
},
}
since filter will always return an array(empty or not) which value always is true.