How to close Modal de Materialize CSS with Vue - vue.js

I am trying to close a Modal of Materialize CSS if the validation is correct but I can not find the form.
The simplest thing was to do a type validation:
v-if = "showModal" and it works but leaves the background of the Modal and although click does not disappear. The background is a class named 'modal-overlay'
This is my code:
<i class="material-icons modal-trigger tooltipped" style="margin-left: 2px;
color:#ffc107; cursor:pointer;" #click="getById(article), fillSelectCategories(),
titleModal='Edit', type='edit'" data-target="modal1">edit</i>
I imported M from the JS file of MaterilizeCSS
import M from "materialize-css/dist/js/materialize.min";
Method:
update(){
var elem = document.querySelectorAll('.modal');
var instance = M.Modal.getInstance(elem);
console.log(instance)
That returns 'undefined'
I tried this too on the update() method:
var elem = document.querySelectorAll('.modal');
elem.close();
M.Modal.close()
I initialize the modal from mounted and it works fine but I can not close it at the moment I require it.
mounted(){
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems, options);
}
But I know what else to try :(

It really is difficult to know why things aren't working for you without looking further into your code, but I've created this simple example to demonstrate how it could be done ..
new Vue({
el: "#app",
data: {
modalInstance: null,
closeAfterTimeElapsed: true,
seconds: 1
},
mounted() {
const modal = document.querySelector('.modal')
this.modalInstance = M.Modal.init(modal)
const select = document.querySelector('select');
M.FormSelect.init(select);
M.updateTextFields();
},
methods: {
handleClick() {
if (this.closeAfterTimeElapsed) {
setTimeout(() => { this.modalInstance.close() }, this.seconds * 1000)
}
}
}
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<div id="app">
<!-- Modal Trigger -->
<button #click="handleClick" data-target="modal1" class="btn modal-trigger">Modal</button>
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<h4>Modal Header</h4>
<p>A bunch of text</p>
</div>
<div class="modal-footer">
Agree
</div>
</div>
<br>
<br>
<div class="row">
<div class="input-field col s6">
<select v-model="closeAfterTimeElapsed">
<option :value="false">False</option>
<option :value="true">True</option>
</select>
<label>Close Modal After</label>
</div>
<div class="input-field col s6">
<input id="seconds" type="number" v-model="seconds">
<label for="seconds">Seconds</label>
</div>
</div>
</div>
See this JSFiddle

Related

Bind class item in the loop

i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
:loading="isLoading[index]"
here the vue :
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
here the data :
data () {
return {
products : [],
isLoading: false,
}
},
here my add to cart method where i change the state of isLoading :
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
You can change your isLoading to an array of booleans, and your addToCart method to also have an index argument.
Data:
return {
// ...
isLoading: []
}
Methods:
addToCart(product, index) {
// ...
}
And on your button, also include index:
#click="addToCart(product, index)"
By changing isLoading to an empty array, I don't think isLoading[index] = true will be reactive since index on isLoading doesn't exist yet. So you would use Vue.set in your addToCart(product, index) such as:
this.$set(this.isLoading, index, true)
This will ensure that changes being made to isLoading will be reactive.
Hope this works for you.
add on data productsLoading: []
on add to cart click, add loop index to productsLoading.
this.productsLoading.push(index)
after http request done, remove index from productsLoading.
this.productsLoading.splice(this.productoading.indexOf(index), 1)
and check button with :loading=productsLoading.includes(index)
You can create another component only for product card,
for better option as show below
Kindly follow this steps.
place the content of card in another vue component as shown below.
<!-- Product.vue -->
<template>
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</templete>
<script>
export default {
name: "Product",
data() {
return {
isLoading: false
}
},
props: {
product: {
type: Object,
required: true
}
},
methods: {
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
}
}
</script>
Change your component content as shown below.
<template>
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<product :product="product" />
</div>
</div>
</div>
</div>
</templete>
<script>
import Product from 'path to above component'
export default {
components: {
Product
}
}
</script>
so in the above method you can reuse the component in other components as well.
Happy coding :-)

Binding vue components to class name

Alright so I am trying to bind this vue components to a class name so it triggers on every element that has this class but what happens is that it only works with the first element and not with other ones
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" /> <!-- submit comment being only triggered on this one -->
</div>
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" />
</div>
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" />
</div>
As you can see above, I've got 3 divs with class __comment_post so naturally submitComment should be bound to all these 3 divs but what happens is that submitComment is being triggered only on the first one
var app = new Vue({
el:".__comment_post",
data: {
comment: ""
},
methods: {
submitComment: function() {
console.log("Test");
}
}
});
Here is a little example you and others can follow in order to bind vue instance to class names.
Lets say, you would like to bind Vue to multiple existing <div class="comment"> element in HTML.
HTML:
<div class="comment" data-id="1">
<div>
<div class="comment" data-id="2">
<div>
Now, you can try the following logic/code to your example.
JS:
var comments = {
"1": {"content": "Comment 1"},
"2": {"content": "Comment 2"}
}
$('.comment').each(function () {
var $el = $(this)
var id = $el.attr('data-id')
var data = comments[id]
new Vue({
el: this,
data: data,
template: '<div class="comment">{{ content }}<div>'
})
})
I hope this will answer your question :)
The vue instance is mounted on the first found DOM element with the css selector passed to the el option. So the rest two div have no vue instances mounted on them.
So wrap your divs with a wrapper div and mount the vue instance on that wrapper
<div id="app">
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" /> <!-- submit comment being only triggered on this one -->
</div>
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" />
</div>
<div class="__comment_post">
<textarea></textarea>
<input type="submit" v-on:click="submitComment" />
</div>
script
var app = new Vue({
el:"#app",
data: {
comment: ""
},
methods: {
submitComment: function() {
console.log("Test");
}
}
});

Vuejs event modifiers

This is from the docs:
#click.prevent.self will prevent all clicks while #click.self.prevent will only prevent clicks on the element itself.
I tried making a fiddle to actually prevent all clicks but am unsuccessful. Can someone elaborate what this line in the docs actually mean?
Fiddle:
var app = new Vue({
el: '#appp',
methods: {
logger(arg) {
console.log(arg);
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<div id="appp">
<div #click.prevent.self="logger('1')"> 1
<br>
<div #click.prevent.self="logger('2')"> ..2
<br>
<div #click.prevent.self="logger('3')"> ....3
</div>
</div>
</div>
</div>
One of the best ways to see how .prevent and .self interact is looking at the output of the Vue compiler:
.prevent.self:
on: {
"click": function($event){
$event.preventDefault();
if($event.target !== $event.currentTarget)
return null;
logger($event)
}
}
.self.prevent
on: {
"click": function($event){
if($event.target !== $event.currentTarget)
return null;
$event.preventDefault();
logger($event)
}
}
The key difference between those 2 code blocks is inside the fact that the order of the operations matters, a .prevent.self will prevent events coming from its children, but doesn't run any code, but a .self.prevent will only cancel events directly created by itself, and ignores child requests completely.
Demo:
var app = new Vue({
el: '#appp',
data: {log:[]},
methods: {
logger(arg) {
this.log.push(arg);
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<div id="appp" style="display: flex; flex-direction: row;">
<form #submit.prevent="logger('form')" style="width: 50%;">
<button>
<p #click.prevent.self="logger('prevent.self')">
prevent.self
<span>(child)</span>
</p>
<p #click.self.prevent="logger('self.prevent')">
self.prevent
<span>(child)</span>
</p>
<p #click.prevent="logger('prevent')">
prevent
<span>(child)</span>
</p>
<p #click.self="logger('self')">
self
<span>(child)</span>
</p>
<p #click="logger('none')">
none
<span>(child)</span>
</p>
</button>
</form>
<pre style="width: 50%;">{{log}}</pre>
</div>
</div>

v-on:click not working in a child component

First thing first I'm new to vue.js.
what I'm trying to do when the user click on the expander anchor tag in the item-preview component the item-details will display and the item-preview will be hide. Now the problem occurs when the item-preview displayed and i'm trying to toggle it by clicking its own expander anchor tag. I do not whats wrong with this.
Here is my HTML templates.
<script type="text/x-template" id="grid">
<div class="model item" v-for="entry in data">
<item-preview v-bind:entry="entry" v-if="entry.hide == 0">
</item-preview>
<item-details v-bind:entry="entry" v-if="entry.hide == 1">
</item-details>
</div>
</script>
<script type="text/x-template" id="item-preview">
<header class="preview">
<a class="expander" tabindex="-1" v-on:click="toggle(entry)"></a>
<span class="name rds_markup">
{{ entry.name }}
</span>
</header>
</script>
<script type="text/x-template" id="item-details">
<div class="edit details">
<section class="edit" tabindex="-1">
<form action="#">
<fieldset class="item name">
<a class="expander" v-on:click="toggle(entry)"></a>
{{ entry.name }}
</fieldset>
</form>
</section>
</div>
</script>
And here how I called the grid component on my view.
<grid
:data="packages">
</grid>
And for my Vue implementation
var itemPreview = Vue.component('item-preview',{
'template':"#item-preview",
'props':{
entry:Object
},
methods:{
toggle:function(entry){
entry.hide = !!entry.hide;
return true;
}
}
});
var itemDetails = Vue.component('item-details',{
'template':"#item-details",
'props':{
entry:Object
},
methods:{
toggle:function(entry){
entry.hide = !!entry.hide;
return true;
}
}
});
var grid = Vue.component('grid',{
'template':"#grid",
'props':{
data:Array,
},
components:{
'item-preview': itemPreview,
'item-details': itemDetails
},
methods:{
toggle:function(entry){
entry.hide = !!entry.hide;
return true;
}
}
});
var vm = new Vue({
el:'#app',
data:{
message:'Hello',
packages:{}
},
ready:function(){
this.fetchPackages();
},
methods:{
fetchPackages:function(){
this.$http.get(url1,function( response ){
this.$set('packages',response);
});
},
}
});
Silly me. It took me 30minutes to figure out what is wrong with this code.
What I did to fix this is instead of entry.hide = !!entry.hide; I use entry.hide = true in item-preview component and in the item-details entry.hide = false. this fix my issue.

Model data not binding to html template in Backbone,Marionette

I am new to backbone and Marionette.
My requirement is,
I have a main grid having few rows. If i select a row from grid i need to fetch the details and display on the same page.
Binding the grid is working fine. But when i click on the row data is not binding to html template. I am unable to find out the issue.
Below is my html template for row details
<script id="selected-broker-details-tmpl" type="text/x-handlebars-template">
<div id="pnl-broker-details" class="panel panel-default">
<div class="panel-heading">
Broker Details
</div>
<div id="broker-details-container" class="panel-body">
<div class="col-md-6">
<div class="form-group">
<label for="inputbrokerName" class="col-sm-3 control-label">BrokerName</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputbrokerName" placeholder="Broker Name" value="{{BrokerName}}">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputMnemonic" class="col-sm-3 control-label">Mnemonic</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputMnemonic" placeholder="Mnemonic" value="{{Mnemonic}}">
</div>
</div>
</div>
</div>
</div>
</script>
Backbone view declaration
App.Views.BrokerDetails = Backbone.View.extend({
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
el: '#details',
template: brokerTemplates.BrokerDetailsTempalte,
render: function () {
this.$el.html(this.template({}));
}
});
Model and collection declaration
var BrokderDetails = Backbone.Model.extend({
BrokerId: null,
BrokerName: null,
Mnemonic: null,
OASYSMnemonic: null
});
var BrokerDetailsCollection = Backbone.Collection.extend({
initialize: function (options) {
this.model = BrokderDetails;
this.url = '/api/BrokerSelections/SelectedBroker/';
}
,
setParam: function (str) {
this.url = '/api/BrokerSelections/SelectedBroker/' + str;
this.fetch();
},
parse: function (data) {
return data;
}
});
click event in main grid
events: {
"click .selection": "selectedBroker",
},
selectedBroker: function (e) {
var details = new BrokerDetailsCollection();
var brokerdetails = new App.Views.BrokerDetails({ model: null, collection: details });
details.setParam($(e.currentTarget).data("id"));
details.fetch();
brokerdetails.render();
},
Now there are 2 issues,
1. Click event is firing 2 times, if i select a row i main grid
2. Model data is not binding to html template. I mean html template is displayed, but with empty values in textboxes