My modal box is inside of a vue component. When the data is submitted, I want the component to send back the response data to the parent so I can append it to the root element.
The component
<template>
<div v-if="value.startsWith('new')">
<!-- Create Client Modal -->
<div class="modal show" id="modal-create-client" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button " class="close" data-dismiss="modal" aria-hidden="true" #click.prevent="close">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
<!-- Form Errors -->
<div class="alert alert-danger" v-if="createForm.errors.length > 0">
<p><strong>Whoops!</strong> Something went wrong!</p>
<br>
<ul>
<li v-for="error in createForm.errors">
{{ error }}
</li>
</ul>
</div>
<!-- Create Client Form -->
<form class="form-horizontal" role="form">
<!-- Name -->
<div class="form-group">
<label class="col-md-3 control-label">First Name</label>
<div class="col-md-7">
<input id="create-client-name" type="text" class="form-control" #keyup.enter="store" v-model="createForm.first">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Last Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="last" #keyup.enter="store" v-model="createForm.last">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email</label>
<div class="col-md-7">
<input type="text" class="form-control" name="organization" #keyup.enter="store" v-model="createForm.email">
<span class="help-block">Email is required for invoices</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Organization</label>
<div class="col-md-7">
<input type="text" class="form-control" name="organization" #keyup.enter="store" v-model="createForm.organization">
</div>
</div>
</form>
</div>
<!-- Modal Actions -->
<div class="modal-footer" v-if="value == 'newClient'">
<button type="button" class="btn btn-default" data-dismiss="modal" #click.prevent="close">Close</button>
<button type="button" class="btn btn-primary" #click="storeClient">Create</button>
</div>
<div class="modal-footer" v-else-if="value == 'newLead'">
<button type="button" class="btn btn-default" data-dismiss="modal" #click.prevent="close">Close</button>
<button type="button" class="btn btn-primary" #click="storeLead">Create</button>
</div>
<div class="modal-footer" v-else-if="value == 'newContact'">
<button type="button" class="btn btn-default" data-dismiss="modal" #click.prevent="close">Close</button>
<button type="button" class="btn btn-primary" #click="storeContact">Create</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
createForm: {
errors: [],
first: '',
last: '',
email: '',
organization: ''
},
};
},
props: ['value'],
/**
* Prepare the component (Vue 1.x).
*/
ready() {
this.prepareComponent();
},
/**
* Prepare the component (Vue 2.x).
*/
mounted() {
var vm = this
this.prepareComponent();
},
methods: {
/**
* Prepare the component.
*/
prepareComponent() {
$('#modal-create-client').on('shown.bs.modal', () => {
$('#create-client-name').focus();
});
$("#modal-create-client").on("hide.bs.modal", function(e) {
$(this).removeData('bs.modal');
});
},
close() {
$('#modal-create-client').removeClass('show');
},
/**
* Create a new client for the user.
**/
storeClient() {
this.persistClient(
'post', './clients/add',
this.createForm, '#modal-create-client'
);
},
storeLead() {
this.persistClient(
'post', './leads/add',
this.createForm, '#modal-create-client'
);
},
storeContact() {
this.persistClient(
'post', './contacts/add',
this.createForm, '#modal-create-client'
);
},
/**
* Persist the client to storage using the given form.
*/
persistClient(method, uri, form, modal) {
form.errors = [];
this.$http[method](uri, form).then(response => {
location.reload();
$(modal).modal('hide');
}).catch(response => {
if (typeof response.data === 'object') {
form.errors = _.flatten(_.toArray(response.data));
} else {
form.errors = ['Something went wrong. Please try again.'];
}
});
},
watch: {
value: function (value) {
// update value
$(this.$el).val(value)
},
}
}
}
</script>
The root Element
var MyComponent = Vue.component('my-ajax-component',
require('./components/Toolbar.vue') );
new Vue({
el: '#select',
data: {
selected: ''
},
components: {
// <my-component> will only be available in parent's template
'my-ajax-component': MyComponent
}
});
and my view
<div class="form-group clearfix">
<div class="col-xs-12" id="select">
{!! Form::label('client_id', 'Choose Client:', ['class' => 'control-label']) !!}
{!! Form::select('client_id', ['newClient' => 'New Client', $clients], null, ['title' => 'Select Client', 'class' => 'form-control selectpicker', 'v-model' => 'selected', 'data-live-search' => 'true']) !!}
<br>
<my-ajax-component v-bind:value="selected"></my-ajax-component>
</div>
</div>
Instead of location reload I want to append the response data to the select element which is my roo
I changed my root element to
new Vue({
el: '#select',
data: {
selected: '',
data: ''
},
components: {
// <my-component> will only be available in parent's template
'my-ajax-component': MyComponent
},
methods: {
handler: function(data) {
console.log('this is my data' + data)
}
}
my component now has
this.$emit('data-received',response)
and put v-on in the child component
<my-ajax-component v-bind:value="selected" v-on:data-received='handler(data)'></my-ajax-component>
I get data undefined or nothing
I can see the data returned in the post .. it's the id of my object ...should I json encode it
The easiest way can be to emit the event with data in child component when you get the response.
In child:
this.$emit('data-received',response)
In parrent:
<child-component v-on:data-received='handler(data)'>
In handler function in parrent, do whatever you want with data.
UPDATED:
Your backend should return JSON to follow REST Api standards.
Every endpoint of API should return JSON, even if it is simple string.
Instead of
In parrent:
<child-component v-on:data-received='handler(data)'>
I used In parrent:
<child-component v-on:data-received='handler'>
Related
<template>
<b-form #submit.prevent="Submit" class="mb-5">
<div class="inputArea" v-for="input in inputs" :key="input.id">
<b-form-group label-cols-sm="2" label="Solution (EN)">
<ckeditor :editor="ckeditor" v-model="form.body.en" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.en']">
<div v-for="err in errors['body.en']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
<b-form-group label-cols-sm="2" label="Body (FR)">
<ckeditor :editor="ckeditor" v-model="form.body.np" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.np']">
<div v-for="err in errors['body.np']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
<b-form-group label-cols-sm="2" label="Body (IT)">
<ckeditor :editor="ckeditor" v-model="form.body.in" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.in']">
<div v-for="err in errors['body.in']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
</div>
<b-form-group label="" label-cols-sm="2">
<b-button type="button" class="text-white" variant="dark" #click="addRow">Add row</b-button>
</b-form-group>
<b-form-group label="" label-cols-sm="2">
<b-button type="submit" class="text-white" variant="dark">Submit</b-button>
</b-form-group>
</b-form>
</template>
<style lang="scss">
</style>
<script>
import CKEditor from '#ckeditor/ckeditor5-vue2'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic'
export default {
name: 'Interaction',
components: {
ckeditor: CKEditor.component
},
data(){
return{
counter: 0,
inputs: [
{
en: '',
np: '',
in: '',
}],
form: {
body: [
{
en: '',
np: '',
in: '',
}
],
},
errors: {},
ckeditorData: '<p></p>',
ckeditorConfig: {
// The configuration of the editor
},
ckeditor: ClassicEditor
}
},
methods: {
Submit(){
this.storing = true
this.errors = {}
var self = this
axios.post('/this-is-a-post-url', this.form)
.then(function(response){
console.log(response)
})
},
addRow() {
this.inputs.push({
en: '',
it: '',
fr: '',
id: `${++this.counter}`,
value: '',
});
}
}
}
</script>
I will have array coming in the body name so I am trying to to clone the clone body on a click of a button which has a function AddRow. I want to clone the three fields en,np,in and I want it work like normal html works in this. Example when we clone html form it create input field like so <input name="body['en'][0]"> and when we clone another time it creates something like this <input name="body['en'][1]">.
I have the above code, it clones the body but it also clones the added text before cloning. I want to add an empty field while cloning and also want to update v-model. How can I do that?
Refer below example:
https://codepen.io/telen/pen/OeNZVV
<main class="container">
<form id="app" data-apartments='[{ "price": "23000", "rooms": "12" }, { "price": "42000", "rooms": "32" }]'>
<h1>
Dynamic apartment forms
</h1>
<hr>
<div class="row">
<div class="col-xs-2">
<button type="button" v-on:click="addNewApartment" class="btn btn-block btn-success">
Add +
</button>
</div>
<div class="col-xs-10">
Would you like add more apartments?
</div>
</div>
<div v-for="(apartment, index) in apartments">
<div class="row">
<div class="col-xs-2">
<label> </label>
<button type="button" v-on:click="removeApartment(index)" class="btn btn-block btn-danger">
Rem -
</button>
</div>
<div class="form-group col-xs-5">
<label>Price (HUF)</label>
<input v-model="apartment.price" type="number"
name="apartments[][price]" class="form-control" placeholder="Price">
</div>
<div class="form-group col-xs-5">
<label>Rooms (PCS)</label>
<input v-model="apartment.rooms" type="number"
name="apartments[][rooms]" class="form-control" placeholder="Rooms">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<button type="submit" v-on:click.prevent="sumbitForm" class="btn btn-block btn-primary">
Submit
</button>
</div>
<div class="col-xs-10">
Open the console (F12) and see the result
</div>
</div>
<hr>
<pre>{{ $data }}</pre>
</form>
JS:
window.app = new Vue({
el: '#app',
data: {
apartment: {
price: '',
rooms: ''
},
apartments: [],
},
mounted: function () {
/*
* The "data-apartments" could come from serverside (already saved apartments)
*/
this.apartments = JSON.parse(this.$el.dataset.apartments)
},
methods: {
addNewApartment: function () {
this.apartments.push(Vue.util.extend({}, this.apartment))
},
removeApartment: function (index) {
Vue.delete(this.apartments, index);
},
sumbitForm: function () {
/*
* You can remove or replace the "submitForm" method.
* Remove: if you handle form sumission on server side.
* Replace: for example you need an AJAX submission.
*/
console.info('<< Form Submitted >>')
console.info('Vue.js apartments object:', this.apartments)
window.testSumbit()
}
}
})
/*
* This is not Vue.js code, just a bit of jQuery to test what data would be submitted.
*/
window.testSumbit = function () {
if (!window.jQuery) {
console.warn('jQuery not present!')
return false
}
console.info('Submitted (serverside) array:', jQuery('form').serializeJSON())
}
I'm trying to create a modal form that will add a record. I am able to display the default values from data but as soon as I try to modify the field, I get the following error whenever I try to type changes to the input box.
*vue.min.js:6 TypeError: Cannot use 'in' operator to search for 'fullname' in undefined
at a.ke [as $set] (vue.min.js:6)
at input (eval at Ya (vue.min.js:1), <anonymous>:3:2182)
at He (vue.min.js:6)
at HTMLInputElement.n (vue.min.js:6)
at HTMLInputElement.Yr.o._wrapper (vue.min.js:6)*
In given Below I added the code of the component I'm trying to create:
Any help, please.
var bus = new Vue();
Vue.component('leagues_add', {
props: {
show: Boolean,
is_admin: Boolean,
},
data: function () {
return {
newLeague: {"fullname":"a", "notes":"b", "group_image_path": "c"} // remember to always enclose the fieldnames in doublequotes
}
},
methods: {
closeModal() {
this.show = false;
},
showModal() {
this.show = true;
},
addLeague() {
event.preventDefault();
var formData = this.toFormData(this.newLeague);
axios.get("http://"+ window.location.hostname +"/db/leagues/index.php?action=create").then(function(response){
if (response.data.error) {
app.errorMessage = response.data.message;
} else {
app.leagues = response.data.leagues;
}
});
},
toFormData(obj) {
var fd = new FormData();
for (var i in obj) {
fd.append(i, obj[i]);
}
return fd;
},
}
,
template:
`
<!-- Add new Leage -->
<div>
<div class="text-center pb-3" >
<button type="button" class="btn btn-outline-primary bg-success text-white" #click="showModal"><b class="" style="">Add League</b></button>
</div>
<transition name="modal">
<div id="overlay" v-show="this.show">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add League</h5>
<button type="button" class="close" #click="closeModal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form action="#" method="POST">
<div class="form-group">
<input type="text" v-model="this.newLeague.fullname" class="form-control form-control-md" placeholder="Name of League">
</div>
<div class="form-group">
<textarea v-model="this.newLeague.notes" rows="3" cols="100%" name="notes" class="form-control form-control-md" placeholder="Describe this league">
</textarea>
</div>
<div class="form-group form-inline ">
<div class="col-12 p-0">
<input type="url" v-model="this.newLeague.group_image_path" class="col-5 pull-left form-control form-control-md" placeholder="Image URL">
<button class="col-4 btn btn-primary btn-md">Image</button>
</div>
</div>
<div class="form-group">
<button class="btn btn-info btn-block btn-md" #click="closeModal();addLeague();">Add this league</button>
</div>
</form>
</div>
</div>
</div>
</div>
</transition>
<div>
`
});
<div class="row">
<div class="col-md-12">LEAGUES SECTION</div>
</div>
<div class="row mt-2">
<div class="col-md-12">
<leagues_add :show="true" />
</div>
</div>
The problem is here:
v-model="this.newLeague.fullname"
You cannot use this. with v-model. Instead it should be:
v-model="newLeague.fullname"
You should also remove all other references to this within your template. In many cases they are harmless but sometimes, such as with v-model, they will cause problems.
Complete examples below. Note how the first input does not function correctly when editing the text.
new Vue({
el: '#app1',
data () {
return { newLeague: { fullname: 'League 1' } }
}
})
new Vue({
el: '#app2',
data () {
return { newLeague: { fullname: 'League 1' } }
}
})
<script src="https://unpkg.com/vue#2.6.11/dist/vue.js"></script>
<div id="app1">
<input type="text" v-model="this.newLeague.fullname">
{{ newLeague.fullname }}
</div>
<div id="app2">
<input type="text" v-model="newLeague.fullname">
{{ newLeague.fullname }}
</div>
I followed the way #skirtle wrote the data section and it worked.
My original syntax was:
data: function () {
return {
newLeague: {"fullname":"a", "notes":"b", "group_image_path": "c"} }
}
to
data () {
return { newLeague: { fullname: 'League 1' } }
}
I am working on Vue.JS and I tried to use local-storage with it to save data. In my code, I can store and retrieve all data with local-storage except line-through effect. Here, I am trying to store actual boolean value of line-through effect in local-storage and want to retrieve that value on to-do list app.
<title>To Do List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<style>
.taskDone {
text-decoration: line-through;
}
</style>
</head>
<body>
<div id="todo-list" class="container">
<div class="container col-sm-8 col-sm-offset-2">
<h1 class="text-center"> <big><b> To Do List </b> </big></h1>
<h5 class="text-center"> <span v-show="itemsTodo.length"> ({{ itemsTodo.length }} pending) </span></h5>
<div class="col-md-8">
<button v-if="state === 'default'" class="btn btn-primary" #click="changeState('edit') ">Add Item</button>
<button v-else class="btn btn-info" #click="changeState('default')">Cancel</button>
</div>
<br>
<br>
<div v-if="state === 'edit'" >
<div class="col-sm-4">
<input class='form-control' v-model="newItem" type="text" placeholder="Type here" #keyup.enter="saveItem" >
</div>
<div class="col-sm-4">
<input class="form-control" v-model="newdate" type="date" type="text"/>
</div>
<div class="col-sm-4">
<button class='btn btn-primary btn-block' v-bind:disabled="newItem.length === 0"#click= "saveItem">Save Item</button>
</div>
</div>
<br>
<br>
<ul type="none" class="list-group">
<li class="list-group-item" v-for="(item,index,date) in items" :class="{taskDone : item.completed}" >
<h4>
<input type="checkbox" v-model="item.completed" #click="item.completed = !item.completed">
<button class="btn btn-primary " #click.stop="removeitems(index)">× </button>
<b><i> {{ item.label }} {{ item.date }} </i></b></h4>
</li>
</ul>
<h2 v-if="items.length === 0">Nice Job! Nothing in TO DO LIST</h2>
<div class="col-sm-4">
<button class="btn btn-warning btn-block" #click="clearcompleted"> Clear Completed</button>
</div>
<div class="col-sm-4">
<button class="btn btn-danger btn-block" #click="clearAll"> Clear All</button>
</div>
</div>
</div>
2. Vue.JS code
<script src="https://unpkg.com/vue" ></script>
<script>
var todolist = new Vue({
el: '#todo-list',
data : {
state : 'edit',
header: 'To Do List',
newItem: '',
newdate: '',
items: [
{
label:'coffee',
completed:false,
date:'2019-06-20' ,
},
{
label:'tea',
completed:false,
date:'2019-06-19' ,
},
{
label:'milk',
completed:false,
date:'2019-06-19' ,
},
]
},
computed:{
itemsDone(){
return this.items.filter(items => items.completed)
},
itemsTodo(){
return this.items.filter(items =>! items.completed)
},
},
methods:{
saveItem: function(){
if (this.newItem != ''){
this.items.push({
label:this.newItem,
completed: false,
date : this.newdate,
});
this.newItem = '';
this.newdate = '';
}},
changeState: function(newState){
this.state = newState;
this.newItem = '';
this.newdate = '';
},
removeitems(index){
this.items.splice(index,1);
},
clearcompleted (){
this.items = this.itemsTodo;
},
clearAll: function(){
this.items = [ ];
},
},
mounted(){
console.log('App Mounted!');
if (localStorage.getItem('items')) this.items = JSON.parse(localStorage.getItem('items'));
},
watch: {
items:{
handler(){
localStorage.setItem('items',JSON.stringify(this.items));
},
},
},
});
</script>
I expect correct boolean value of line-through effect to be stored in local-storage. So that, appropriate effect will show on browser.
You are just watching items. If you change something in a item (in your case completed) the handler will not be called and your change is not stored.
You could use a "deep" watcher but i suggest to call your save logic whenever you changed something.
I have a vuejs component that displays a modal dialog with a small form inside. When the form is submitted I would like to hide the Modal but cannot figure out how to do it. When submitted the form calls a method in the parent.
Here is the component code
<template>
<div>
<div id="todoModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{ title }}</h4>
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<div class="modal-body">
<form id="todoForm" #submit.prevent="$emit('save')">
<div class="form-group">
<label for="name">Todo name</label>
<input
id="name"
v-model="todo.name"
type="text"
class="form-control"
aria-describedby="nameHelp"
placeholder="Enter Todo Name"
/>
<small id="nameHelp" class="form-text text-muted"
>Enter your todo's name</small
>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary mr-4" type="submit" form="todoForm">
<span v-if="mode == 'create'">Create</span>
<span v-if="mode == 'update'">Update</span>
</button>
<button
type="button"
class="btn btn-danger mr-auto"
data-dismiss="modal"
#click="
$parent.showModal = false;
$parent.getTodos();
"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "CreateTodo",
props: ["mode", "title", "todo", "showModal"],
ref: "createTodoModal",
mounted() {
if (this.mode == "create") {
this.title = "Create Todo";
}
},
methods: {}
};
</script>
<style scoped></style>
And here is my APP.js file
<template>
<div id="app" class="container mt-5">
<router-view
ref="createtodo"
class="CreateTodo"
name="a"
:todo="todo"
:title="title"
:mode="mode"
:show-modal="showModal"
#save="saveTodo"
></router-view>
</div>
</template>
<script>
import { APIService } from "./APIServices";
const apiService = new APIService();
export default {
name: "App",
data: function() {
return {
mode: "create",
title: "Create Todo",
todo: {},
todos: [],
numberOfTodos: 0,
showModal: false
};
},
mounted: function() {
this.getTodos();
},
methods: {
saveTodo: function() {
if (this.mode == "create") {
apiService.createTodo(this.todo).then(
result => {
if (result.status === 200) {
this.todo = result.data;
this.getTodos();
}
},
error => {}
);
this.showModal = false;
// this.$refs.createtodo.$refs.todoModal
} else if (this.mode == "update") {
apiService.updateTodo(this.todo).then(
result => {
this.getTodos();
},
error => {}
);
this.showModal = false;
} else if (this.mode == "update") {
apiService.updateTodo(this.todo).then(
result => {
this.showModal = false;
this.getTodos();
},
error => {}
);
}
},
}
};
</script>
<style lang="scss">
</style>
I tried using the ref to reference the Modal from APP.js but it does not work.
Add an id to the close X button"
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close">
<span aria-hidden="true">×</span>
</button>
Then create a method to close the modal:
closeModal() {
document.getElementById('close').click();
},
Like #Dan Stoian reply, you can use ref in vue.js :
<button ref="Close" type="button" data-dismiss="modal" ...>
...
</button>
And in your handler
this.$refs.Close.click();
If you are using boostrap, you need to call the hide an show methods from it, because modal api create html elements on the fly (as the dark background)
I recommend to create a save method instead of call the $emit, where you can call the modal hide method before emit the save signal.
<script>
import $ from 'jquery'
export default {
name: "CreateTodo",
props: ["mode", "title", "todo"],
ref: "createTodoModal",
mounted() {
if (this.mode == "create") {
this.title = "Create Todo";
}
},
methods: {
save() {
$('#ModalId').modal('hide')
this.$emit('save')
}
}
};
</script>
showModal is not needed in this case.
You might use v-if to show/hide modal
In your component:
<div v-if="showModal">
<div id="todoModal" class="modal fade" role="dialog">
...
</div>
</div>
and set showModal to true/false to show/hide component respectively.
Child
<template>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby=""
aria-hidden="true" ref="modalEle">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-primary text-white">
<h5 class="modal-title" id="exampleModalLabel">{{ title }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<slot name="body" />
</div>
<div class="modal-footer">
<slot name="footer"></slot>
<button ref="Close" type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { onMounted, ref, defineProps, defineExpose } from "vue";
import { Modal } from "bootstrap";
defineProps({
title: {
type: String,
default: "<<Title goes here>>",
},
});
let modalEle = ref(null);
let thisModalObj = null;
onMounted(() => {
thisModalObj = new Modal(modalEle.value);
});
function _show() {
thisModalObj.show();
}
function _close(){
thisModalObj.hide()
}
defineExpose({ show: _show, close: _close });
</script>
Parent
<template>
<Modal title="OMG ITS A MODAL" ref="thisModal">
<template #body>
<div class="col-md-12 mx-auto">
yay modal text
</div>
</template>
<template #footer>
<!-- extra footer stuff !-->
</template>
</Modal>
</template>
<script setup>
import { ref } from 'vue';
import Modal from "../components/ModalCard.vue";
let showModal = ()=>{
thisModal.value.show();
}
let closeModal = ()=>{
thisModal.value.close();
}
</script>
Explanation
So basically what we are doing is exposing a child function to the parent via refs. In the _show and _close functions we are triggering the .show() and .hide() they are bootstrap modal functions we have access too via the thisModalObj. I hope this helps!
Now you can progmatically call thisModal.value.show and thisModal.value.close and itll show and close the modal.
you can use this npm package
npm i vue-js-modal
https://www.npmjs.com/package/vue-js-modal
Your code should then be modified in this way:
<template>
<modal :name="'edit-modal'+id" height="auto">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit {{ mName }}</h5>
<button type="button" class="close" #click="hideEditModal(id)">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="/user/update" method="patch" #submit.prevent="updateAssistant">
<div class="modal-body">
<div class="position-relative form-group">
<label for="exampleAddress" class="">Full name</label><input name="name" v-model="editName" id="exampleAddress" placeholder="FullName" type="text" class="form-control">
<div v-if="errors.has('editName')" class="alert alert-danger">
{{ errors.first('editName') }}
</div>
</div>
<div class="position-relative form-group">
<label for="exampleEmail11" class="">Email</label><input name="email" v-model="editEmail" id="exampleEmail11" placeholder="email" type="email" class="form-control">
<div v-if="errors.has('editEmail')" class="alert alert-danger">
{{ errors.first('editEmail') }}
</div>
</div>
<div class="position-relative form-group">
<label for="examplePassword11" class="">Change Password</label><input name="password" v-model="editPassword" id="examplePassword11" placeholder="password" type="password" class="form-control">
<div v-if="errors.has('password')" class="alert alert-danger">
{{ errors.first('password') }}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" #click="hideEditModal(id)">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
<span class="loader" v-if="this.loading" style="position: absolute; bottom: 0.515rem; left: 20px;">
<span class="ball-clip-rotate">
<div style=" border:1px solid #000;"></div>
</span>
</span>
</form>
</modal>
import Errors from '../../Errors.js'
export default {
name: 'AssistantEditModalComponent',
props: [
'mEmail',
'mName',
'id'
],
data () {
return {
editPassword: null,
disabled: false,
errors: Errors,
loading: false
}
},
methods: {
hideEditModal(id) {
this.$modal.hide('edit-modal'+id);
},
setData() {
this.editName = this.mName
this.editEmail = this.mEmail
},
updateAssistant() {
this.disabled = true;
this.loading = true;
const form = {
editName: this.mName,
editEmail: this.mEmail,
password: this.editPassword
}
axios.patch('/user/update/'+this.id, form)
.then((response) => {
this.disabled = false
this.loading = false
this.hideEditModal(this.id)
this.alert(response)
})
.catch((err) => {
this.disabled = false
this.loading = false
Errors.fill(err.response.data.errors)
})
},
alert(response) {
swal(response.data.username, response.data.message, 'success')
},
},
computed: {
editName: {
get: function() {
return this.mName
},
set: function(value) {
this.$emit('update:mName', value);
}
},
editEmail: {
get: function() {
return this.mEmail
},
set: function(value) {
this.$emit('update:mEmail', value);
}
}
}}
If you don't want to add any extra Close button rather than default X button of modal header you could do something like this:
<b-modal
id="user-role"
ref="role-modal"
hide-footer
>
...
</b-modal>
then in your method:
hideModal() {
this.$refs["role-modal"].$refs['close-button'].click()
}
My component vue is like this :
<template>
<div class="modal" tabindex="-1" role="dialog">
...
<div class="form-group">
<input type="file" id="change-image" name="replace">
</div>
<div class="form-group">
<input type="text" class="form-control" id="alt-image">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Set
</label>
</div>
...
<button type="button" class="btn btn-success" #click="editImageProduct">
{{trans('store.modal.edit.button.save')}}
</button>
...
</div>
</template>
<script>
export default{
...
methods: {
editImageProduct(event) {
// get the data
}
}
}
</script>
When I click the button, I want get value from input type file, input type text and intput type checkbox
I know use javascript or jquery
But I want to get it use vue.js 2
How can I do it?
With checkbox and text input, you can use v-model.
With file input you can get data when user upload image, use event onChange
Example code:
new Vue({
el: '#app',
data: {
image: '',
altImage: '',
set: false,
},
methods: {
onUpload(e) {
this.image = e.target.files || e.dataTransfer.files;
},
editImageProduct() {
console.log('File object', this.image);
console.log('Image name', this.image[0].name);
console.log('Alt Image', this.altImage);
console.log('Set', this.set);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="app">
<div class="form-group">
<input type="file" #change="onUpload">
</div>
<div class="form-group">
<input type="text" class="form-control" v-model="altImage">
</div>
<div class="checkbox">
<label><input type="checkbox" v-model="set"> Set</label>
</div>
<button type="button" class="btn btn-success" #click="editImageProduct">Save</button>
</div>
use v-model in your form
<input type="file" id="change-image" name="replace" v-model="file">
<input type="text" class="form-control" id="alt-image" v-model="text">
<input type="checkbox" v-model="checkbox">
export default {
data: function(){
return {
file: null,
checkbox: null,
text: null,
}
},
methods: {
editImageProduct() {
console.log(this.file, this.checkox, this.text);
}
}
}
EDITED:
try to look into this example for file inputs, hope it'll help you http://codepen.io/Atinux/pen/qOvawK/