I have a list of items rendered with v-for. I want each item to have a "?" that is clickable to show a modal containing a description for that specific item. My issue right now is that when the "?" is clicked, it shows the modal for every item in the v-for. How do i solve this?
<div
v-for="(item, index) in items"
:key="index"
>
<div>
{{ item.name }}
<div>
<span #click="itemModal = true">
?
</span>
<div v-show="itemModal">
{{ item.description }}
<button #click="itemModal = false">
Close modal
</button>
</div>
</div>
</div>
</div>
export default {
data() {
return {
itemModal: false
}
}
}
Your itemModal property is share with all items currently, so you need one modal status for each item.
eg. you can create a toggle method to update an array of modal status:
<div
v-for="(item, index) in items"
:key="index"
>
<div>
{{ item.name }}
<div>
<span #click="toggle(index)">
?
</span>
<div v-show="itemModal[index]">
{{ item.description }}
<button #click="toggle(index)">
Close modal
</button>
</div>
</div>
</div>
</div>
export default {
data() {
return {
itemModal: []
}
},
methods: {
toggle(index) {
this.$set(this.itemModal, index, !this.itemModal[index])
}
}
}
nb: an array (or an object) is not reactive in depth, so we have to use Vue.$set (cf. docs)
Related
I'm building a small project where it has a component in it, I should render the data from the API.
Here is my code:
<template>
<div>
<p v-if="$fetchState.pending">Fetching products...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<div v-else>
<h1>Nuxt products</h1>
<ul>
<li
v-for="(product, key) of product"
:key="product.id"
:img="product.img"
>
{{ product.description }}
</li>
</ul>
<button #click="$fetch">Refresh</button>
</div>
</div>
</template>
<script>
export default {
async fetch() {
this.products = await this.$axios("https://dummyjson.com/products");
},
};
</script>
and here is the error code:
Property or method "product" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property
This works
<template>
<div>
<p v-if="$fetchState.pending">Fetching products...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<div v-else>
<h1>Nuxt products</h1>
<ul>
<li v-for="product in products" :key="product.id" :img="product.img">
{{ product.description }}
</li>
</ul>
<button #click="$fetch">Refresh</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products: [],
};
},
async fetch() {
const response = await this.$axios.$get('https://dummyjson.com/products')
this.products = response.products
},
}
</script>
You need v-for="product in products" as explained here: https://vuejs.org/guide/essentials/list.html
Also, regarding the the network request
We can see that as usual, the actual data is inside data, hence you can use the $get shortcut: https://axios.nuxtjs.org/usage#-shortcuts
Then you need to access the products field to have the data to iterate on. Using the Vue devtools + network tab greatly helps debugging that one!
so the answer is i missed putting the data as #kissu has mentioned above
<template>
<div>
<p v-if="$fetchState.pending">Fetching products...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<div v-else>
<h1>Nuxt products</h1>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.description }}
{{ product.images }}
</li>
</ul>
<button #click="$fetch">Refresh</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products: [],
};
},
async fetch() {
const response = await this.$axios.$get("https://dummyjson.com/products");
this.products = response.products;
},
};
</script>
I am new to Vue and am using the Bootstrap modals to display product information. I have grid containers that each have a product picture, description, and two buttons. One of the buttons(More details >>), when clicked, would shoot a modal window that should show the very same product description and picture of the grid it was contained in.
<div id="myapp">
<h1> {{ allRecords() }} </h1>
<div class="wrapper" >
<div class="grid-container" v-for="product in products" v-bind:key="product.ID">
<div class="Area-1">
<img class="product_image" src="https:....single_product.jpg">
</div>
<div class="Area-2">
<div class = "amount">
{{ product.amount }}
</div>
{{ product.Description }}
</div>
<div class="Area-3">
<b-button size="sm" v-b-modal="'myModal'" product_item = "'product'">
More Details >>
</b-button>
<b-modal id="myModal" >
<h1> {{ product.Name }} </h1>
<h3> {{ product.Description }} </h3>
</b-modal>
</div>
<div class="Area-4">
<br><button>Buy</button>
</div>
</div>
</div>
</div>
var app = new Vue({
'el': '#myapp',
data: {
products: "",
productID: 0
},
methods: {
allRecords: function(){
axios.get('ajaxfile.php')
.then(function (response) {
app.products = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
})
Area 1, 2 and 4 work perfectly fine and they display the product data according to the v-for value and as expected respectively for each grid container. Area 3 is a problem here when I click the More details >> button, I just see a faded black screen. I am not sure what I am doing wrong here, would really appreciate some help.
Add a property selectedProduct, then on More Details button click event, assign the current product to the selectedProduct member as below :
HTML
<div class="Area-3">
<b-button size="sm" v-b-modal="'myModal'"
#click="selectProduct(product)">More Details >> </b-button>
<b-modal id="myModal">
<h1> {{ this.selectedProduct.Name }} </h1>
<h3> {{ this.selectedProduct.Description }} </h3>
</b-modal>
</div>
Javascript:
var app = new Vue({
'el': '#myapp',
data: {
products: "",
productID: 0,
selectedProduct: {Name: '', Description: '', Amount:0}
},
methods: {
allRecords: function(){
...
},
selectProduct: function(product)
{
this.selectedProduct = product;
}
...
}
I can't replicate the issue. I created JSFiddle to test:
https://jsfiddle.net/4289wh0e/1/
However, I realized multiple modal elements are displayed when I click on the "More Details" button.
I suggest you add only one modal in the wrapper and store the chosen product in a data variable.
https://jsfiddle.net/4289wh0e/2/
<div id="myapp">
<h1> {{ allRecords() }} </h1>
<div class="wrapper">
<div class="grid-container" v-for="product in products" v-bind:key="product.ID">
<div class="Area-1"><img class="product_image" src="https:....single_product.jpg"> </div>
<div class="Area-2">
<div class="amount">{{ product.amount }} </div>
{{ product.Description }}</div>
<div class="Area-3">
<b-button size="sm" v-b-modal="'productModal'" #click="chooseProduct(product)" product_item="'product'">More Details >> </b-button>
</div>
<div class="Area-4">
<br>
<button>Buy</button>
</div>
</div>
<b-modal id="productModal" v-if="chosenProduct">
<h1> {{ chosenProduct.Name }} </h1>
<h3> {{ chosenProduct.Description }} </h3>
</b-modal>
</div>
</div>
Vue.use(BootstrapVue)
var app = new Vue({
'el': '#myapp',
data: {
products: [],
chosenProduct: null
},
methods: {
chooseProduct: function (product) {
this.chosenProduct = product
},
allRecords: function(){
this.products = [
{
ID: 1,
Description: 'dek',
Name: 'Name',
amount: 100
},
{
ID: 2,
Description: 'dek 2',
Name: 'Name 2',
amount: 300
}
]
},
}
})
The reason you're just seeing a black screen is because you're not giving the b-modal in your v-for a unique ID.
So when you click the button it's actually opening all the modals at the same time, and stacking the backdrop making it look very dark.
Instead you could use your product ID (I'm guessing it's unique) in your modal ID to make it unique
<div id="myapp">
<h1> {{ allRecords() }} </h1>
<div class="wrapper" >
<div class="grid-container" v-for="product in products" v-bind:key="product.ID">
<div class="Area-1">
<img class="product_image" src="https:....single_product.jpg">
</div>
<div class="Area-2"><div class = "amount">{{ product.amount }} </div>
{{ product.Description }}
</div>
<div class="Area-3">
<b-button size="sm" v-b-modal="`myModal-${product.ID}`" product_item = "'product'">
More Details >>
</b-button>
<b-modal :id="`myModal-${product.ID}`" >
<h1> {{ product.Name }} </h1>
<h3> {{ product.Description }} </h3>
</b-modal>
</div>
<div class="Area-4">
<br><button>Buy</button>
</div>
</div>
</div>
</div>
Example pen:
https://codepen.io/Hiws/pen/qBWJjOZ?editors=1010
I'm using a Vue.js v-for loop to output a table of information, each with their own action buttons like so using Element UI library.
<template>
<div class="card">
<div class="card-header">
<tool-bar></tool-bar>
</div>
<div class="card-body">
<el-table :data="orders" v-loading="loading" current-row-key="index" empty-text="No products found">
<el-table-column type="expand">
<template slot-scope="props">
<el-tabs>
<el-tab-pane label="Order Items">
<ul>
<li v-for="(product, index) in orders[props.$index].products" :key="index">{{ product.name }}</li>
</ul>
</el-tab-pane>
<el-tab-pane label="Customer Details">Customer Details
<!-- <p v-for="(customer, index) in orders[props.$index].order.billing_address" :key="index">{{ customer.index }}</p> -->
</el-tab-pane>
</el-tabs>
</template>
</el-table-column>
<el-table-column label="Order ID" prop="order.id"></el-table-column>
<el-table-column label="Customer" prop="order.billing_address.first_name"></el-table-column>
<el-table-column label="Due Time" prop="order.due_time"></el-table-column>
<el-table-column
align="right">
<template slot="header" slot-scope="scope">
<el-input
v-model="search"
placeholder="Type to search"/>
</template>
<template slot-scope="scope">
<el-button size="mini" type="success" :disabled="orders[scope.$index].checked_in" :loading="false" :ref="'btn-' + scope.$index" #click="checkInOrder(scope.$index, scope.row)">{{ (orders[scope.$index].checked_in) ? 'Checked in' : 'Check in' }}</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
<script>
import Toolbar from '../components/Toolbar.vue';
export default {
components: {
'tool-bar': Toolbar
},
mounted() {
this.fetchOrders();
},
data () {
return {
search: '',
}
},
computed: {
loading() {
return this.$store.getters.loading;
},
orders() {
return this.$store.getters.orders;
}
},
methods: {
fetchOrders() {
this.$store.dispatch('fetchOrders')
.then(res => {
})
.catch(err => {
})
},
checkInOrder(index, row) {
this.$refs['btn-' + index].loading = true;
axios.post('/order/update', {
id: row.order.id,
status: 'bakery',
products: row.products
})
.then(res => {
this.$refs['btn-' + index].loading = false;
})
.catch(err => {
this.$refs['btn-' + index].loading = false;
})
}
}
}
</script>
When I click one of the buttons, I want to be able to set the :loading attribute of the clicked button to true as well as change the button label to Loading... until a given Ajax request is completed.
I used the :ref attribute on the button and, when the button is clicked, I alter the attribute as follows:
checkInOrder(index, row) {
this.$refs['btn-' + index].loading = true;
}
This seems to work fine, but the console is throwing a warning, so I want to find out the way to achieve this.
The warning I get is this:
I believe it's prompting you to link :loading to a property, which you can set, rather than mutating the element prop directly. Thus, when you call checkInOrder() you could just update the boolean property that :loading is linked to.
I believe this question is relevant and will help you fix this issue.
I have two lists , user can drag items from list 1 to list 2 and there is a button with text input so user can add his own input to the list 2 which will be automatically updated in my MYSQL database using axios.
This is AddItem script
addItembh(){
var input = document.getElementById('itemFormbh');
if(input.value !== ''){
// this line makes a new article with input value but no attribute :(
this.tasksNotCompletedNew.unshift({
behv_skilldesc:input.value
});
axios.post('../joborder/addAttrib', {
behv_skilldesc: input.value,
type:'behvnew',
joborder_id: this.joborder_id ,
alljobs_id: this.alljobs_id
}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
});
input.value='';
}
},
To be clear on the question : I need to assign an attribute to my new article thats getting created so I can find the text of that attrib later on deleteItem method
UPDATE :
<template>
<div class="row">
<div class="col-md-4 col-md-offset-2">
<section class="list">
<header>Drag or Add Row Here</header>
<draggable class="drag-area" :list="tasksNotCompletedNew" :options="{animation:200, group:'status',handle:'disabled'}" :element="'article'" #add="onAdd($event, false)" #change="update">
<article class="card" v-for="(task, index) in tasksNotCompletedNew" :key="task.prof_id" :data-id="task.prof_id" #change="onChange">
<span >
{{ task.prof_skilldesc }}
</span>
<span v-if="task.prof_skilldesc !== 'Drag Here'">
<button class="pull-left" #click="deleteItem(task.prof_id) + spliceit(index)" ><i class="fa fa-times inline"></i></button>
</span>
</article>
<article class="card" v-if="tasksNotCompletedNew == ''">
<span>
Drag Here
</span>
</article>
</draggable>
<div>
<input id='itemForm' />
<button v-on:click='addItem' class="btn btn-theme btn-success" style='margin-top:5px;' >Add a row </button>
</div>
</section>
</div>
<div class="col-md-4">
<section class="list">
<header>List of Skills ( Hold left click )</header>
<draggable class="drag-area" :list="tasksCompletedNew" :options="{animation:200, group:'status'}" :element="'article'" #add="onAdd($event, true)" #change="update">
<article class="card"
v-for="(task, index) in visibleskills"
:key="task.prof_id" :data-id="task.prof_id"
>
{{ task.prof_skilldesc }}
<div v-if="index == 4" style="display:none" >{{index2 = onChange(index)}}</div>
</article>
<pagination
v-bind:tasksCompletedNew ="tasksCompletedNew"
v-on:page:update ="updatePage"
v-bind:currentPage ="currentPage"
v-bind:pageSize="pageSize">
</pagination>
</draggable>
</section>
</div>
</div>
</template>
So on Add a row our method will be called .
Thanks for any help
I have one button, when I click I want to display data only if the value of the checkbox is true, If it false, it's display when DOM is created
But I can't please look my code.
Template.students.helpers({
all_students: () => {
return students.find();
}
});
Template.body.onCreated(() => {
Meteor.subscribe('students');
});
Template.students.events({
'submit .insert': (e) => {
e.preventDefault();
students.insert({
name: e.target[0].value,
age: e.target[1].value,
check: false
});
this._checkValue(e);
},
'click .is-delete': (e) => {
students.remove(e.currentTarget.id);
},
'click .check-checkbox': (e) => {
students.update(e.currentTarget.id, {
$set: {
check: !this.check
}
})
},
'click .all': () => {
// HERE
}
})
<template name="students">
<div class="content menu">
<ul>
<button class="ui button all">All list</button> <!-- THIS BUTTON -->
{{#each all_students}}
<li class="content-list" id="{{ _id }}">
<div class="name">{{ name }}</div>
<div class="age">{{ age }} ans</div>
<span id="{{ _id }}" class="delete is-delete"></span>
<div class="ui checkbox">
<input id="{{ _id }}" class="check-checkbox" type="checkbox" name="check">
</div>
</li>
{{/each}}
</ul>
</div>
</template>
Inside of my event handler click .all if I try to return students.find() it doesn't work.
The easiest way is to use a ReactiveVar to flag if the list should show like so:
Add the ReactiveVar to your template instance
Template.students.onCreated(() => {
this.showAllStudents = new ReactiveVar(false);
this.subscribe('students');
});
Then expose it with a helper:
Template.students.helpers({
showStudents() {
Template.instance().showAllStudents.get();
},
all_students() {
students.find();
};
});
In your template, test for the flag
<template name="students">
<div class="content menu">
<ul>
<button class="ui button all">All list</button> <!-- THIS BUTTON -->
{{#if showStudents}}
{{#each all_students}}
<li class="content-list" id="{{ _id }}">
<div class="name">{{ name }}</div>
<div class="age">{{ age }} ans</div>
<span id="{{ _id }}" class="delete is-delete"></span>
<div class="ui checkbox">
<input id="{{ _id }}" class="check-checkbox" type="checkbox" name="check">
</div>
</li>
{{/each}}
{{/if}}
</ul>
</div>
</template>
And add the event handler which just switches the state (ie. set opposite of current state):
Template.students.events({
'click .all': (event, instance) => {
instance.showAllStudents.set(!instance.showAllStudents.get());
}
})
If you haven't already got it, run meteor add reactive-var to get the package.
And if you're using imports, use import { ReactiveVar } from 'meteor/reactive-var'; to import it.