Dynamically create v-model from form input field in VueJS - vue.js

I want to create a form dynamically from a json response obtained from backend.
Here is the code:
<template>
<div class="container">
<div v-for="field in form">
<div v-if="field.type === 'text'">
<input type="text" :name="field.name" :placeholder="field.label"/>
</div>
<div v-else-if="field.type === 'radio'">
<div v-for="option in field.options">
<label>
<input type="radio" :name="field.name" :value="option">
<span class="text">{{ option }}</span>
</label>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
form: [
{
name: 'first_name',
label: 'First Name',
type: 'text',
},
{
name: 'last_name',
label: 'Last Name',
type: 'text',
},
{
name: 'gender',
label: 'Gender',
type: 'radio',
options: ['male','female'],
}
],
response: [], <!--I want to populate this array with form response.-->
}
}
}
</script>
Now, I don't know how many fields to be created and don't know the name. I get a different response from each different request. So I need a way to fill the response[] array with form data. The response[] array may look like this:
response: [
{
name: 'first_name',
value: 'Yeasir',
},
{
name: 'last_name',
value: 'Arafat',
},
{
name: 'gender',
value: 'male',
}
]
How can I achieve the result? It would be a great help.

Related

How to remove html tags

Hi everyone I want to not show "html tags" When i have data in tables, but i want show text only like microsoft word, I'm not sure on the support, I don't know to fix it and I have tried many times, I think can't to remove all the html tags from string, I used CKeditor to input and datatable of vue output from vueX
help me please
Example Outpout
<template>
<div class="container" id="annoucements">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary card-header-icon">
<div class="card-icon">
<i class="material-icons">assignment</i>
</div>
<h4 class="card-title">
{{ $t('global.table') }}
<strong>{{ $t('cruds.annoucement.title') }}</strong>
</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="table-overlay" v-show="loading">
<div class="table-overlay-container">
<material-spinner></material-spinner>
<span>Loading...</span>
</div>
</div>
<datatable
:columns="columns"
:data="data"
:total="total"
:query="query"
:xprops="xprops"
:HeaderSettings="false"
:pageSizeOptions="[10, 25, 50, 100]"
>
<global-search :query="query" class="pull-left" />
<span style="margin-left:10%">
<button
type="button"
class="btn btn-default"
#click="fetchIndexData"
:disabled="loading"
:class="{ disabled: loading }"
>
<i class="material-icons" :class="{ 'fa-spin': loading }">
refresh
</i>
{{ $t('global.refresh') }}
</button>
</span>
<header-settings :columns="columns" class="pull-right" />
</datatable>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import TranslatedHeader from '#components/Datatables/TranslatedHeader'
import HeaderSettings from '#components/Datatables/HeaderSettings'
import GlobalSearch from '#components/Datatables/GlobalSearch'
import DatatableAttachments from '#components/Datatables/DatatableAttachments'
export default {
components: {
GlobalSearch,
HeaderSettings
},
data() {
return {
columns: [
{
title: 'cruds.annoucement.fields.id',
field: 'id',
thComp: TranslatedHeader,
sortable: true,
colStyle: 'width: 100px;'
},
{
title: 'cruds.annoucement.fields.annoucement',
field: 'annoucement',
thComp: TranslatedHeader,
tdComp: DatatableAttachments
},
{
title: 'cruds.annoucement.fields.name',
field: 'name',
thComp: TranslatedHeader,
sortable: true
},
{
title: 'cruds.annoucement.fields.number',
field: 'number',
thComp: TranslatedHeader,
sortable: true
},
{
title: 'cruds.annoucement.fields.short_name',
field: 'short_name',
thComp: TranslatedHeader,
sortable: true
},
{
title: 'cruds.annoucement.fields.allow_date',
field: 'allow_date',
thComp: TranslatedHeader,
sortable: true
},
{
title: 'cruds.annoucement.fields.description',
field: 'description',
thComp: TranslatedHeader,
}
],
query: { sort: 'id', order: 'desc', limit: 100, s: '' },
xprops: {
module: 'AnnoucementsIndex',
route: 'annoucements',
permission_prefix: 'annoucement_'
}
}
},
beforeDestroy() {
this.resetState()
},
computed: {
...mapGetters('AnnoucementsIndex', ['data', 'total', 'loading'])
},
watch: {
query: {
handler(query) {
this.setQuery(query)
this.fetchIndexData()
},
deep: true
}
},
methods: {
...mapActions('AnnoucementsIndex', [
'fetchIndexData',
'setQuery',
'resetState'
])
}
}
</script>
Use method below for each cell or make an copy of data that contains string without html:
removeHtmlTags(htmlString) {
const tmp = document.createElement('DIV');
tmp.innerHTML = htmlString;
return tmp.textContent || tmp.innerText || '';
}

How to load the form elements and its attribute dynamically

I want to load the template and its form elements dynamically.
The desired output:
I want to load all these fields dynamically so that form should be generic and I can use the same template for all forms in my project.
The code I have tried:
<template>
<b-card>
<b-row>
<b-col sm="3">
<b-form-group>
<label v-for="option in labelNames">{{ option.name }}</label>
<input :type="text" :id="name" :class="form-control" :placeholder="Enter your name" :v-validate="'required|Name'" :name="Firstname" v-model="firstName">
<span v-show="errors.has(':name')" class="is-danger">{{ errors.first(':name') }}</span>
</b-form-group>
</b-col>
</b-row>
</b-card>
</template>
<script>
export default {
name: 'addEmpl',
data () {
return {
labelNames: [
{ name: 'FirstName'},
{ name: 'LastName'},
{ name: 'MiddleName'},
{ name: 'EmployeeID'},
{ name: 'Gender'},
],
inputs: [
{ type: 'text', id : 'name1', class : 'form-control' placeholder : 'Enter your name' name: 'Firstname' v-validate : 'required'},
{ type: 'text', id : 'name2', class : 'form-control' placeholder : 'Enter your middle name' name: 'Middlename' v-validate : 'required'},
{ type: 'text', id : 'name3', class : 'form-control' placeholder : 'Enter your last name' name: 'Lastname' v-validate : 'required'},
],
}
}
}
</script>
Kindly suggest me a better option to do generic forms. Thanks in advance

how to add edit button on vue-good-table in vue

I m new to Vue and stuck in a situation and don't know how to do that if anybody suggests me how I can do this let me show my code first
<div class="table-responsive-sm">
<vue-good-table
title="Shop List Table"
:columns="columns"
:rows="rows"
:paginate="true"
:lineNumbers="true"
:globalSearch="true" >
<template slot="table-row" slot-scope="props" ><a class="btn btn-sm primary" #on-row-click="onRowClick">save</a></template>
</vue-good-table>
and in script
data(){
return{
columns: [
{
label: 'Brand Name',
field: 'brand_name',
},
{
label: 'Brand Desc',
field: 'brand_desc',
},
{
label: 'Action',
field: 'before',
},
],
rows:[],
}
}
getTotals(){
var self = this;
var new1=[];
this.$http.get('/api/brands')
.then(function (response) {
self.rows=response.data
})
},
now my problem is that if I use
<span v-if="props.column.field == 'before'">
before
</span>
as suggested in this https://jsfiddle.net/aks9800/hsf0sqf8/ it throws an error like field not defined I just want to add an extra action button for edit this is vue-good table one more thing none of the action as suggested in this link for eg:- #on-row-click="onRowClick" not working
Try this
<div class="table-responsive-sm">
<vue-good-table
title="Shop List Table"
:columns="columns"
:rows="rows"
:paginate="true"
:lineNumbers="true"
:globalSearch="true" >
<template slot="table-row" slot-scope="props" >
<a class="btn btn-sm primary" #on-row-click="onRowClick">save</a>
</template>
<template slot="table-row" slot-scope="props">
<span v-if="props.column.field == 'actions'">
<a class="btn btn-sm primary" #on-row-click="onRowClick">save</a>
</span>
<span v-else>
{{props.formattedRow[props.column.field]}}
</span>
</template>
</vue-good-table>
</div>
data(){
return{
columns: [
{
label: 'Brand Name',
field: 'brand_name',
},
{
label: 'Brand Desc',
field: 'brand_desc',
},
{
label: 'Actions',
field: 'actions',
sortable: false,
}
],
rows:[],
}
}
getTotals(){
var self = this;
var new1=[];
this.$http.get('/api/brands')
.then(function (response) {
self.rows=response.data
})
},
Here is very good example how to add "edit" button in a row by marekfilip
https://jsfiddle.net/marekfilip/jm4ywzor/
html:
<div id="app">
<vue-good-table
:columns="columns"
:rows="rows" >
<template slot="table-row" slot-scope="props">
<span v-if="props.column.field == 'before'">
<button #click="editRow(props.row.id)">Edit</button>
<button #click="deleteRow(props.row.id)">Delete</button>
</span>
<span v-else>
{{props.formattedRow[props.column.field]}}
</span>
</template>
</vue-good-table>
<span>{{ text }}</span>
</div>
javascript
new Vue({
el: '#app',
data() {
return {
columns: [
{
label: 'Before',
field: 'before'
},
{
label: 'ID',
field: 'id',
sortable: true,
},
{
label: 'Text',
field: 'text',
type: 'number',
sortable: true,
},
],
rows: [
{ text: 'A', id: 1 },
{ text: 'B', id: 2 },
{ text: 'C', id: 3 },
{ text: 'D', id: 5 },
],
text: ''
};
},
methods: {
editRow(id) {
this.showAlert(id, 'EDIT')
},
deleteRow(id) {
this.showAlert(id, 'DELETE')
},
showAlert(id, type) {
this.text = `You clicked ${type} on row ID ${id}`
}
}
});

VueJS Custom dropdown buttons not working independently of each other

So I have a button dropdown which is working as expected but I have a bug where I can't reuse the same component as they both dont work independently of each other but instead when one is clicked the other changes too.
Please find a JSFiddle below and my code.
Thanks
<div id="app">
<div v-on:click="menuVisible = !menuVisible" class="dropdownBtn">
<div v-bind:class="{ active : menuVisible }"class="dropdownBtn__title">
<span v-if="!btnTitle">exploring</span>
<span v-else>{{ btnTitle }}</span>
</div>
<div v-show="menuVisible" class="dropdownBtn__content">
<ul v-for="reason in reasons">
<li v-on:click="updateTitle(reason)">{{ reason.title }}</li>
</ul>
</div>
</div>
<div v-on:click="menuVisible = !menuVisible" class="dropdownBtn">
<div v-bind:class="{ active : menuVisible }"class="dropdownBtn__title">
<span v-if="!btnTitle">exploring</span>
<span v-else>{{ btnTitle }}</span>
</div>
<div v-show="menuVisible" class="dropdownBtn__content">
<ul v-for="reason in reasons">
<li v-on:click="updateTitle(reason)">{{ reason.title }}</li>
</ul>
</div>
</div>
</div>
new Vue({
el: '#app',
data() {
return {
menuVisible: false,
btnTitle: false,
reasons: [{
title: 'family fun',
value: 1
},
{
title: 'relaxing',
value: 2
},
{
title: 'dining',
value: 3
},
{
title: 'meetings & events',
value: 4
},
{
title: 'what\'s on',
value: 5
},
{
title: 'gold',
value: 6
}]
}
},
methods: {
updateTitle($event) {
this.btnTitle = $event.title
}
}
})
So, for one, you haven't actually made a reusable component for the dropdown. You need to define that using Vue.component. Then you can use the tag for the custom component in the root template.
Secondly, if you are binding to the same data, then that is what will be reflected in both templates. You'll still need to pass separate data to the two separate dropdown components.
Vue.component('dropdown', {
template: `
<div v-on:click="menuVisible = !menuVisible" class="dropdownBtn">
<div v-bind:class="{ active : menuVisible }"class="dropdownBtn__title">
<span v-if="!btnTitle">exploring</span>
<span v-else>{{ btnTitle }}</span>
</div>
<div v-show="menuVisible" class="dropdownBtn__content">
<ul v-for="reason in reasons">
<li v-on:click="updateTitle(reason)">{{ reason.title }}</li>
</ul>
</div>
</div>
`,
props: ['menuVisible', 'btnTitle', 'reasons'],
methods: {
updateTitle($event) {
this.btnTitle = $event.title
}
}
})
new Vue({
el: '#app',
data() {
return {
fooReasons: [
{ title: 'family fun', value: 1 },
{ title: 'relaxing', value: 2 },
{ title: 'dining', value: 3 },
{ title: 'meetings & events', value: 4 },
{ title: 'what\'s on', value: 5 },
{ title: 'gold', value: 6 }
],
barReasons: [
{ title: 'family bar', value: 1 },
{ title: 'bar relaxing', value: 2 },
{ title: 'bar dining', value: 3 },
{ title: 'meetings & bars', value: 4 },
{ title: 'bar\'s on', value: 5 },
{ title: 'gold bar', value: 6 }
]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
<dropdown :menu-visible="false" :btn-title="false" :reasons="fooReasons"></dropdown>
<dropdown :menu-visible="false" :btn-title="false" :reasons="barReasons"></dropdown>
</div>

Vue.js nested for loop input field model binding

In this example I am allowing the user to create their own typed list of sections. Each type has it's own form fields. The form fields render properly however, if I enter data into one of the fields after I've created two duplicate sections, both inputs are updated with the typed in text. This is not the intended result.
Instead each section should update its form field data content individually and it should reflect back to the value stored within the data.section related to it.
What am I missing?
Laravel View
{{Form::open(['route' => 'api.post.store', 'class' => 'form-horizontal'])}}
<fieldset>
<div id="legend">
<legend class="">Register</legend>
</div>
<div :key="section.id" v-for="(index,section) in sections" class="control-group form-group-lg">
<div class="form-header">
<h3>#{{ section.label }}</h3>
</div>
<pre>#{{ section | json }}</pre>
<div v-for="field in section.fields" :key="field.id">
<div class="text-field" v-show="field.inputType == 'text'">
<label class="control-label" :for="section.name">#{{ field.label }}</label>
<div class="controls">
<input v-model="field.data.content" class="input-xlarge form-control">
<p class="help-block">#{{ field.helpText }}</p>
</div>
</div>
<div class="text-area-field" v-show="field.inputType == 'text-area'">
<label class="control-label" :for="section.name">#{{ field.label }}</label>
<div class="controls">
<textarea :v-bind="field.data.content" class="input xlarge form-control" :placeholder="field.placeholder">
#{{ field.data.content }}
</textarea>
</div>
</div>
<div class="text-area-field" v-show="field.inputType == 'data-map'">
<label class="control-label" :for="section.name">#{{ field.label }}</label>
<div class="controls">
<textarea :v-bind="field.data.content" class="input xlarge form-control" :placeholder="field.placeholder">
#{{ field.data.content }}
</textarea>
</div>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<div class="dropdown">
<a data-target="#" href="page.html" data-toggle="dropdown" class="dropdown-toggle">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li v-for="sectionType in sectionTypes">
<a #click="setSectionCreateType(sectionType)" href="#">#{{ sectionType.label }}</a>
</li>
</ul>
</div>
</div>
<div class="controls">
<div #click="addSection()" class="btn bdn-success" class="btn btn-success">Add Section</div>
<div #click="savePost()" class="btn bdn-success" class="btn btn-success">Save</div>
</div>
</div>
</fieldset>
{{Form::close()}}
Vuefile
<script type="text/javascript">
import Vue from 'vue';
import FormField from './create/FormField.vue';
export default {
components: {
FormField,
},
ready: function () {
},
filters: {},
data(){
return {
messages: [],
sections: [],
saveSections: [],
sectionCreateType: false,
sectionTypes: [
{
label: 'Company',
map: 'company',
fields: [
{
label: 'name',
name: 'name',
inputType: 'text',
placeholder: 'Company Name',
data: {
content: '',
},
},
{
label: 'symbol',
name: 'symbol',
inputType: 'text',
placeholder: 'stock symbol',
data: {
content: '',
},
}
]
},
{
label: 'Link',
map: 'link',
inputType: 'text',
data: {},
fields: [
{
label: 'url',
name: 'url',
inputType: 'text',
placeholder: 'Url',
data: {
content: '',
},
},
]
},
{
label: 'Paragraph',
map: 'paragraph',
data: {},
fields: [
{
label: 'content',
name: 'content',
inputType: 'text-area',
placeholder: 'Content',
data: {
content: '',
},
},
]
},
{
label: 'Person',
map: 'person',
data: {},
inputType: 'data-map',
'fields': [
{
label: 'first_name',
name: 'name',
placeholder: 'Person Name',
data: {
content: '',
},
},
{
label: 'last_name',
name: 'name',
placeholder: 'Person Name',
data: {
content: '',
},
}
]
},
],
}
},
directives: {},
events: {},
methods: {
setSectionCreateType(type)
{
console.log('setting sectionCreateType: ' + type.label)
this.sectionCreateType = type;
},
addSection()
{
if (!this.sectionCreateType) {
this.sectionCreateType = this.sectionTypes[0];
}
this.createSection(this.sectionCreateType);
},
createSection(type)
{
this.sections.push(Vue.util.extend({}, type))
},
previewPost(){
},
savePost: function(){
var view = this;
var saveObject = [];
var sectionObject = [];
this.sections.forEach(function (section) {
if(!sectionObject[section.type.map])
{
sectionObject[section.type.map] = [];
}
for (var key in section.type.fields) {
var field = section.type.fields[key];
var saveKey = [];
saveKey[field.name] = field.data.content;
}
sectionObject[section.type.map].push(saveKey);
});
saveObject.push(sectionObject);
console.log(saveObject);
},
}
}
</script>
You are using the same v-model so VueJS does what it should do.
You have to create e.g. list of models and somehow handle index (e.g. take it from v-for for every section/subsection and use v-model='list[index].field