New to Vuejs 2, need a bit of help to understand how this would be done.
So, I have a template that looks like the following:
<template>
<div class="wrapper">
<div class="item" v-for="item in items">
<div class="item">
<div class="title">{{ item.title }}</div>
<div class="action">
<a href="#" #click.prevent="editSettings(item, $event)">
Click Me
</a>
</div>
</div>
<div v-if="showSettings" class="settings">
<!-- Settings component for this item. -->
<settings-panel item="item"></settings-panel>
</div>
</div>
</div>
</template>
The scripts looks like this:
export default {
data() {
return {
items: [
// This data is from an API usually and only
// shown here for example purposes
{ id: 1, title: 'Title 1' },
{ id: 2, title: 'Title 2' },
{ id: 3, title: 'Title 3' },
{ id: 4, title: 'Title 4' }
],
showSettings: false
};
},
methods: {
editSettings(item, event) {
// Only show the clicked items settings, not all
this.showSettings = !showSettings;
}
}
}
What is the easiest and cleanest approach to only showing the settings panel for the clicked item? Right now, if I click the Click Me settings, all settings open up. The data listed in the code is only there for example, but is coming from an API so I don't have much to do with the manipulation of that data.
Can anyone help lead me in the right direction?
Instead of using showSettings add a selectedItem.
export default {
data() {
return {
items: [
// This data is from an API usually and only
// shown here for example purposes
{ id: 1, title: 'Title 1' },
{ id: 2, title: 'Title 2' },
{ id: 3, title: 'Title 3' },
{ id: 4, title: 'Title 4' }
],
selectedItem: null
};
},
methods:{
selectItem(item){
if (this.selectedItem === item) this.selectedItem = null
else this.selectedItem = item
}
}
}
And modify your template to set the selectedItem when the item is clicked and show the settings only if the selectedItem is the current item.
<template>
<div class="wrapper">
<div class="item" v-for="item in items">
<div class="item">
<div class="title">{{ item.title }}</div>
<div class="action">
<a href="#" #click.prevent="selectItem(item)">
Click Me
</a>
</div>
</div>
<div v-if="selectedItem === item" class="settings">
<!-- Settings component for this item. -->
<settings-panel item="item"></settings-panel>
</div>
</div>
</div>
</template>
The above will show the settings for the clicked item if the currently selected item is not the item that was clicked. If the currently selected item is the one that was clicked, it will hide the settings.
Related
User information is managed by the state of the store.js file.
User information is managed by the state of the store.js file.
const store = createStore({
state() {
return {
users:[
{id: 0, userName: 'test1', wallet: 500},
{id: 1, userName: 'test2', wallet: 1000},
{id: 2, userName: 'test3', wallet: 1500},
{id: 3, userName: 'test4', wallet: 2000},
],
userName: '',
updateUserName: '',
userLoginInfomation: '',
errorMessage: ''
};
},
A modal is displayed when you press the button to view the wallet.
↓The modal that appears when you click View Wallet.
<div class="overlay" v-show="showContent" #click="closeModal">
<transition name="modal">
<div v-show="showContent" class="content">
<p>{{ viewUsers[1].userName }} balance</p>
<p>{{ viewUsers[1].wallet }}yen</p>
<p>
<button class="close-button" #click="closeModal">Close</button>
</p>
</div>
</transition>
</div>
↓The modal that appears when you click send.
<div class="overlay" v-show="showContent2" #click="closeModal">
<div class="content">
<p> Your balance:500yen</p>
<p>Amount to send</p>
<input type="text" class />
<p>
<button class="close-button" #click="closeModal2">Close</button>
</p>
</div>
</div>
What you want to achieve
(1) When you click the View Wallet button, you want to get the user name with the same index number as the clicked index number from state.users in the store.js file and display it modally.
(2) When you click the send button, enter the amount to send to the displayed modal input. I want to add the amount of money entered in the wallet of the state.users data of the store.js file that has the same sequence number as the clicked button.
This is untested, but should help you get in the right direction:
<template>
<ul>
<li v-for="user in users" :key="user.id" #click="selectUser(user)">
{{ user.userName }} | {{ user.wallet }}
</li>
</ul>
<div class="modal" v-if="showModal">
<!--
here you can now access whatever user properties
you want via the selectedUser property
-->
<p>Name: {{ selectedUser.userName }}</p>
<p>ID: {{ selectedUser.id }}</p>
<p>Wallet: {{ selectedUser.wallet }}</p>
</div>
</template>
<script>
data: () => ({
selectedUser: null
}),
computed: {
users() {
return this.$store.users;
}
},
methods: {
selectUser(user) {
this.selectedUser = user;
this.showModal = true;
}
},
</script>
sorry I'm still new to reactive vue models and updating I'm trying to draw a line through an input element if a box is checked.
so far I have this setup:
data: {
selected: null,
checked: null,
list: [
{
id: 0,
category: 'Bakery',
food: ['bread','muffins','pie']
},
{
id: 1,
category: 'Fruits',
food: ['apple','bananna','orange']
},
{
id: 2,
category: 'Diary',
food: ['cheese','milk','yogurt']
}
],
isHidden: true,
form: {},
},
my html is as follows (this is a single page app)
<li v-for="food in item.food" class="list-group-item">
<input :class="{marked:food == checked}" #click="checked = food" type="checkbox"> {{ food }}</input>
</li>
this is the css i'm trying to implement
.marked{
text-decoration: line-through;
}
I'm not sure what I need to do to my #click to make it work but so far nothing happens and the class is not applied. Can someone give me tips?
An <input> element can't have content.
So you've got this structure:
<input>{{ food }}</input>
But that's misleading as the <input> tag will be closed automatically. What you'll end up with will actually be some text next to a checkbox, not inside it.
You probably want something similar to this:
<label :class="{marked: food === checked}" #click="checked = food">
<input type="checkbox"> {{ food }}
</label>
There are some other problems involving deselection and multiple selections. I've tried to fix those in the example below:
new Vue({
el: '#app',
data: {
checked: [],
list: [
{
id: 0,
category: 'Bakery',
food: ['bread','muffins','pie']
},
{
id: 1,
category: 'Fruits',
food: ['apple','bananna','orange']
},
{
id: 2,
category: 'Diary',
food: ['cheese','milk','yogurt']
}
]
}
})
.marked{
text-decoration: line-through;
}
<script src="https://unpkg.com/vue#2.6.11/dist/vue.js"></script>
<div id="app">
<ul v-for="item in list">
<li v-for="food in item.food" class="list-group-item">
<label :class="{marked: checked.includes(food)}">
<input type="checkbox" v-model="checked" :value="food">{{ food }}
</label>
</li>
</ul>
</div>
I have this accordion with three arrows. When you click on the arrow it should transform 180deg. I want to have a function that takes the parameter set in the function and tells the data property to change to zero.
I've tried
let vm = this;
vm.$data.arrowOne = 0;
And this[arrow] = 0,
And this.arrow = 0
And it's not working.
Here is my code.
<div class="uk-accordion-ekstra">
<ul uk-accordion="multiple: true">
<li>
<a #click="rotate(arrowOne)" class="uk-accordion-title" href="#">Headline
<img :style="{ transform: 'rotate('+ arrowOne + 'deg)'}" src="IMGSRC"></a>
<div class="uk-accordion-content">
<p>TEXT</p>
</div>
</li>
<li>
<a #click="rotate(arrowTwo)" class="uk-accordion-title" href="#">Headline
<img :style="{ transform: 'rotate('+ arrowTwo + 'deg)'}" src="IMGSRC"></a>
<div class="uk-accordion-content">
<p>TEXT</p>
</div>
</li>
<li>
<a #click="rotate(arrowThree)" class="uk-accordion-title" href="#">Headline
<img :style="{ transform: 'rotate('+ arrowThree + 'deg)'}" src="IMGSRC"></a>
<div class="uk-accordion-content">
<p>TEXT</p>
</div>
</li>
</ul>
</div>
And VUE
new Vue({
el: '.uk-accordion-ekstra',
data: {
arrowOne: 180,
arrowTwo: 180,
arrowThree: 180
},
methods: {
arrow: function(arrow) {
if(this.arrow = 0) {
return this.arrow = 180;
}
}
}
});
I have succesfully managed to do it with a switch. But it aren't as beautiful. And im unsure of what i don't get. So help is appreciated.
You have a structural and a scope problem.
You are referencing this.arrow in a method called arrow, and you pass an argument called arrow - try to differentiate with the names, or you can get messed up
You are repeating stuff that you don't need to. Vue is great for creating components for the smallest of elements - you can use it to make your code shorter, more readable and more effective.
The snippet below makes everything easier:
you have one arrow per component, and if you solve the rotation problem in one place, then it's solved everywhere, and the arrow referenced always connects to the component you edit
you can encapsulate your arrow rotation into one component - no need to "litter" the Vue instance with such small animation
I added #click.prevent that's like preventDefault(), so there won't be a jump to the top when you click an <a></a>
Vue.component('accordion', {
props: ['title', 'text'],
template: '<div><a #click.prevent="rotateArrow()" class="uk-accordion-title" href="#">{{ title }} <i class="fa fa-arrow-circle-o-up" :style="`transform: rotate(${rotation}deg)`"></i></a><div class="uk-accordion-content"><p>{{ text }}</p></div></div>',
data() {
return {
rotation: 0
}
},
methods: {
rotateArrow() {
this.rotation = !this.rotation ? 180 : 0
}
}
})
new Vue({
el: '.uk-accordion-ekstra',
data: {
accordionItems: [{
title: 'Headline 1',
text: 'Text 1'
},
{
title: 'Headline 2',
text: 'Text 2'
},
{
title: 'Headline 3',
text: 'Text 3'
},
]
}
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="uk-accordion-ekstra">
<ul uk-accordion="multiple: true">
<li v-for="accordionItem in accordionItems" :key="accordionItem.title">
<accordion :title="accordionItem.title" :text="accordionItem.text"></accordion>
</li>
</ul>
</div>
I wonder if I use array as model for multiple-checkbox list, how can I check which items is checked and which are unchecked efficiently rather than compare one by one with that array?
<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" #change="handleTasks(task)">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>
new Vue({
data: {
tasks: [
{ title: 'Go to the store' },
{ title: 'Clean the house' },
{ title: 'Learn Vue.js' }
],
selectedTasks: []
},
})
You could add a property to each task (e.g., checked) and bind that to each input's v-model, making it trivial in code to check whether a task is checked/selected:
new Vue({
el: '#app',
data() {
return {
tasks: [
{ title: 'Go to the store', checked: false },
{ title: 'Clean the house', checked: false },
{ title: 'Learn Vue.js', checked: false }
]
};
},
methods: {
clearCheckedTasks() {
this.tasks = this.tasks.filter(x => !x.checked);
}
}
})
<script src="https://unpkg.com/vue#2.5.16"></script>
<div id="app">
<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" v-model="task.checked">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>
<button #click="clearCheckedTasks">Clear checked tasks</button>
<h3>tasks (live)</h3>
<pre>{{tasks}}</pre>
</div>
based on your comment that "I also want to know if one item is checked or unchecked when I click on it", I would use the DOM Event object to detect if it's checked.
demo: https://jsfiddle.net/jacobgoh101/m480bupd/6/
add #click="clickHandler" to the input
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" #change="handleTasks(task)" #click="clickHandler">
use e.target.checked to get the checked
methods: {
clickHandler(e) {
console.log(e.target.checked);
},
// ...
}
Use the loop index:
<li v-for="(task, index) in tasks">
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks[index]" #change="handleTasks(task)">
<label :for="task.title">{{task.title}}</label>
</li>
The data in my app.js file is not being interpolated and displayed on the screen. I tried the older v-repeat. Could it be some missing items in the installation? Any help would be appreciated.
Here is my html
<!-- show the events -->
<div class="col-sm-6">
<div class="list-group">
<a href="#" class="list-group-item" v-for="event in events">
<!-- <h1>{{text}}</h1> -->
<h4 class="list-group-item-heading">
<i class="glyphicon glyphicon-bullhorn"></i>
{{ event.name }}
</h4>
<h5>
<i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
{{ event.date }}
</h5>
<p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>
<button class="btn btn-xs btn-danger" v-on="click: deleteEvent($index)">Delete</button>
</a>
</div>
</div>
And here is my js file
new Vue({
data: {
text: 'hello world',
event: { name: '', description: '', date: '' },
events: []
},
// Anything within the ready function will run when the application loads
ready: function() {
// When the application loads, we want to call the method that initializes
// some data
this.fetchEvents();
},
// Methods we want to use in our application are registered here
methods: {
// We dedicate a method to retrieving and setting some data
fetchEvents: function() {
var events = [
{
id: 1,
name: 'TIFF',
description: 'Toronto International Film Festival',
date: '2015-09-10'
},
{
id: 2,
name: 'The Martian Premiere',
description: 'The Martian comes to theatres.',
date: '2015-10-02'
},
{
id: 3,
name: 'SXSW',
description: 'Music, film and interactive festival in Austin, TX.',
date: '2016-03-11'
}
];
// $set is a convenience method provided by Vue that is similar to pushing
// data onto an array
this.$set('events', events);
},
// Adds an event to the existing events array
addEvent: function() {
if(this.event.name) {
this.events.push(this.event);
this.event = { name: '', description: '', date: '' };
}
}
}
});
Thanks for any help.
So, there are a few issues here. I've cleaned them up for you to look over.
Added the el: "#app" property to tell Vue where to mount your Vue.
Changed your ready to mounted (you could also use created).
Changed this.$set('events',events) to this.events = events.
Added the unreferenced deleteEvent method.
Fixed the click handler syntax for v-on:click.
So the code ends up looking like this.
new Vue({
el: "#app",
data: {
text: 'hello world',
event: { name: '', description: '', date: '' },
events: []
},
mounted: function() {
this.fetchEvents();
},
// Methods we want to use in our application are registered here
methods: {
// We dedicate a method to retrieving and setting some data
fetchEvents: function() {
var events = [...];
this.events = events;
},
// Adds an event to the existing events array
addEvent: function() {
if(this.event.name) {
this.events.push(this.event);
this.event = { name: '', description: '', date: '' };
}
},
deleteEvent(){
alert('delete this one')
}
}
});
Template
<div id="app">
<!-- show the events -->
<div class="col-sm-6">
<div class="list-group">
<a href="#" class="list-group-item" v-for="event in events">
<!-- <h1>{{text}}</h1> -->
<h4 class="list-group-item-heading">
<i class="glyphicon glyphicon-bullhorn"></i>
{{ event.name }}
</h4>
<h5>
<i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
{{ event.date }}
</h5>
<p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>
<button class="btn btn-xs btn-danger" v-on:click=" deleteEvent(event)">Delete</button>
</a>
</div>
</div>
</div>
Working example.