Subcomponent value binded to the property of another instance of the same vue component - vue.js

I have an issue with a custom component. Here's the problem:
This screen is actually 3 times the same Vue component:
<div class="passwords__form">
<InputField class="passwords__field" label="Mot de passe actuel" :password="true" v-model="currentPassword" />
<InputField class="passwords__field" label="Nouveau mot de passe" :password="true" v-model="newPassword" />
<InputField class="passwords__field" label="Répéter le nouveau mot de passe" :password="true" v-model="repeatedPassword" />
<Button title="Changer le mot de passe" #click="updatePassword"/>
</div>
Here's the component code:
<template>
<div
class="field__container"
:class="{ 'field__container--disabled': disabled }"
>
<label
:for="this._uid"
class="field__label"
:class="{ 'field__label--disabled': disabled }"
v-if="labelEnabled"
>{{ label }}</label
>
<input
:id="this._uid"
class="field__input"
:class="{
'left-rounded': !labelEnabled && !password,
'right-rounded': !buttonEnabled && !password
}"
:value="value"
:placeholder="placeholder"
#input="$emit('input', $event.target.value)"
#keyup.enter="$emit('keyup-enter')"
:disabled="disabled"
:type="fieldType"
/>
<input
v-if="password && enableShowPassword"
type="checkbox"
v-model="showPassword"
id="password-checkbox"
class="field__password-checkbox"
/><label
v-if="password && enableShowPassword"
for="password-checkbox"
class="field__password-checkbox-label"
:class="{
'right-rounded': !buttonEnabled,
}"
><span v-if="enableShowPassword && showPassword"><EyeSlash class="field__password-checkbox-icon"/></span><span v-if="!showPassword" ><Eye class="field__password-checkbox-icon field__password-checkbox-icon--eye " /></span></label>
<a
v-if="buttonEnabled"
class="field__button"
#click.stop="$emit('button-click')"
>
{{ button }}
</a>
</div>
</template>
<script lang="ts">
import Component from "vue-class-component";
import Vue from "vue";
import { Prop } from "vue-property-decorator";
import Eye from "../assets/images/icons/eye-regular.svg"
import EyeSlash from "../assets/images/icons/eye-slash-regular.svg"
#Component({
components: {
Eye,
EyeSlash
}
})
export default class InputField extends Vue {
#Prop({ default: "", required: false })
label!: string;
#Prop({ required: true })
value!: string;
#Prop({ default: "", required: false })
placeholder!: string;
#Prop({ default: "", required: false })
button!: string;
#Prop({ default: false, required: false })
disabled!: boolean;
#Prop({ default: false, required: false })
password!: boolean;
#Prop({ default: true, required: false })
enableShowPassword!: boolean;
showPassword = false;
get fieldType(): string {
if (this.password && !this.showPassword) {
return "password";
}
return "text";
}
get labelEnabled(): boolean {
return this.label !== "";
}
get buttonEnabled(): boolean {
return this.button !== "";
}
}
</script>
<style lang="scss">
.field {
&__container {
display: flex;
flex-direction: row;
border: 1px solid $color-grey-7;
font-size: 1.6rem;
transition: all 0.3s;
&:hover:not(&--disabled),
&:focus:not(&--disabled) {
border: 1px solid $color-complementary;
& > .field__label {
background: $color-complementary;
}
}
&--disabled {
cursor: not-allowed;
}
}
&__label {
text-align: center;
padding: 0.5rem 2rem;
border-right: 1px solid $color-grey-8;
background-color: $color-grey-8;
transition: all 0.3s;
&--disabled {
cursor: not-allowed;
}
}
&__input {
flex-grow: 2;
border: none;
color: $color-grey-1;
transition: all 0.3s;
padding: 0 1rem;
&:hover,
&:focus {
outline: none;
}
&--disabled {
cursor: not-allowed;
}
}
&__button {
text-align: center;
padding: 0.5rem 2rem;
border-left: 1px solid $color-grey-7;
transition: all 0.3s;
&:hover,
&:active {
background: $color-grey-7;
}
}
&__password-checkbox {
display: none;
}
&__password-checkbox-label {
background-color: $color-grey-9;
padding: 0.6rem 1rem;
cursor: pointer;
&:hover,
&:active {
background-color: $color-complementary-lighter;
}
}
&__password-checkbox-icon {
width: 1.5rem;
&--eye {
position: relative;
top: 1px;
}
}
}
</style>
I think the problem come from the v-model property on the checkbox. From what I see, the v-model binds to the showPassword property of the first instance of InputField, instead of binding to the current instance of InputField.
I'm not sure why it behaves like that and what my error is, and how to correct it/do it the right way. Does someone have any leads ?

I suppose you should use an unique id for an input type="password" as you did for an usual input :id="this._uid" because on a HTML page all id's declared in elements must be unique.

Related

Vue Accordion with dropdown select filter. How to bind data

I am trying to get a local Vue project working where there is an E-Library Accordion with 3 types of media and a dropdown button to filter between the types of media. I am also trying to get a color coding system going and I attempted this through created a class and trying to bind it (not working). I am trying to filter the media with a method and then applying that method as an #click event to each dropdown button, but I know this is probably poor practice or just not the correct way to do this. Can anyone point me in the right direction as to how to get these two features working correctly? Much appreciated.
This is my page that I am routing to and creating the code on for the Vue project:
<template>
<label for="accordion">Choose type of media:</label>
<select name="accordion-types" id="types">
<option #click="filteredAccordion(index)" value="book">Book</option>
<option #click="filteredAccordion(index)" value="dvd">DVD</option>
<option #click="filteredAccordion(index)" value="stream">Streaming Video</option>
</select>
<div v-for="(accordion, index) in accordions" :key="index">
<button :class="{red: accordions.type === 'Book' }" #click="toggleOpen(index)">
{{ accordion.title }}
</button>
<div class="panel" :class="{open: accordion.isOpen}">
<p>{{ accordion.content }} </p>
<p>{{ accordion.type }}</p>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
accordions: []
};
},
created: function () {
const appData = this;
axios.get("data.json").then(function (response) {
appData.accordions = appData.addIsOpen(response.data.accordions);
});
},
methods: {
addIsOpen: function(items) {
return items.map(function(item) {
item.isOpen = false;
return item;
});
},
toggleOpen: function(index) {
this.accordions[index].isOpen = !this.accordions[index].isOpen;
}
},
computed: {
filteredAccordion: function(items) {
return this.accordions.filter(accordions => !accordions.type.indexOf(this.type));
}
}
};
</script>
<style>
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
background-color: white;
display: none;
overflow: hidden;
}
.panel.open {
display: block;
}
.red {
color: red;
}
</style>

Unwanted animation bug in Vue.js

This is an unwanted animation bug that seems to be normal, but I want the element to be animationed which is in <input v-model="todo"/>. The problem is each time I press on add button to add the todo name (<input v-model="todo"/>), the last element 'last' runs the animation.
P.s. I tried to keep the code as simple as possible.
Vue.createApp({
data() {
return {
todo: "",
todo_list: ['last'],
};
},
methods: {
add() {
this.todo_list.unshift(this.todo);
console.log(this.todo_list);
},
remove(index) {
this.todo_list.splice(index, 1);
},
},
}).mount('#app');
.list-enter-active,
.list-leave-active {
transition: all 200ms ease-out;
}
.list-enter-from {
transform: translateY(-20px);
}
.list-leave-to {
opacity: 0;
transform: translateX(20px);
}
article {
width: 50%;
padding: 10px;
background-color: #dddddd;
border: 1px solid #cfcfcf;
border-radius: 5px;
margin-block: 10px
}
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<input type="text" v-model="todo" /> <button #click="add">add</button>
<transition-group name="list" tag="section">
<article v-for="(todo, index) in todo_list" :key="index" #click="remove(index)">
<span>{{ todo }}</span>
</article>
</transition-group>
</div>
The reason you're experiencing this issue, is because you're using the index as a key.
If you added the elements to the end of the list, this would be fine.
But since you're adding it to the start, it will cause the issue you're seeing.
I'd suggest you make each todo an object, and add a unique identifier to each object. This can be a simple integer that you increment. Then you can use that property as the key.
Example
let id = 1;
Vue.createApp({
data() {
return {
todo: "",
todo_list: [{
id: id++,
value: 'last'
}],
};
},
methods: {
add() {
const todo = {
id: id++,
value: this.todo
}
this.todo_list.unshift(todo);
},
remove(index) {
this.todo_list.splice(index, 1);
},
},
}).mount('#app');
.list-enter-active,
.list-leave-active {
transition: all 200ms ease-out;
}
.list-enter-from {
transform: translateY(-20px);
}
.list-leave-to {
opacity: 0;
transform: translateX(20px);
}
article {
width: 50%;
padding: 10px;
background-color: #dddddd;
border: 1px solid #cfcfcf;
border-radius: 5px;
margin-block: 10px
}
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<input type="text" v-model="todo" /> <button #click="add">add</button>
<transition-group name="list" tag="section">
<article v-for="(todo, index) in todo_list" :key="todo.id" #click="remove(index)">
<span>{{ todo.value }}</span>
</article>
</transition-group>
</div>

How to animate todo moving from one list to another with Vue.js?

I am trying to do this svelte example todo moving animation with Vue.js.
Below you can find what I have done so far. Just click on the todo to see.
new Vue({
el: "#app",
data: {
items: [
{ id: 1, name: 'John', done: false },
{ id: 2, name: 'Jane', done: false },
{ id: 3, name: 'Jade', done: true },
{ id: 4, name: 'George', done: true },
]
},
computed: {
done () {
return this.items.filter(i => i.done)
},
undone () {
return this.items.filter(i => !i.done)
}
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
height: 500px;
transition: all 0.2s;
}
.todos {
display: grid;
grid-template-columns: 1fr 1fr;
}
.todo {
border: 1px solid #ccc;
}
.todo.undone {
grid-column: 2 /span 1;
}
.todo.done {
grid-column: 1 /span 1;
background: blue;
color: white;
}
.flip-list-move {
transition: all 1s ease-in-out;
}
.header-wrapper {
display: grid;
grid-auto-flow: column;
}
.header, .todo {
display: grid;
grid-template-columns: repeat(3, 1fr);
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="header-wrapper">
<div class="header">
<span>Name</span>
<span>Age</span>
<span>Gender</span>
</div>
<div class="header">
<span>Name</span>
<span>Age</span>
<span>Gender</span>
</div>
</div>
<transition-group name="flip-list" tag="div" class="todos">
<div class="todo done" v-for="item of done" :key="item.id" #click="toggle(item)">
<span>{{item.name}}</span>
<span>26</span>
<span>Male</span>
</div>
<div class="todo undone" v-for="item of undone" :key="item.id" #click="toggle(item)">
<span>{{item.name}}</span>
<span>20</span>
<span>Male</span>
</div>
</transition-group>
</div>
In order to animate the todo move from one list to another, I used CSS grid but I can't find a way to distinguish todos (left and right) without having a grid cell which is empty.
I would appreciate if there is a better way to achieve the example in svelte docs or a way to omit the empty cells.
Even though it seemed easy in the beginning, it's a bit tricky.
You can target the first element by tracking the index in the v-for loop. Index 0 is always going to be the first element. And give it the following style:
grid-row-start: 1;
EDIT DEMO:
new Vue({
el: "#app",
data: {
items: [
{ id: 1, name: 'John', done: false },
{ id: 2, name: 'Jane', done: false },
{ id: 3, name: 'Jade', done: true },
{ id: 4, name: 'George', done: true },
]
},
computed: {
done () {
return this.items.filter(i => i.done)
},
undone () {
return this.items.filter(i => !i.done)
}
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
height: 500px;
transition: all 0.2s;
}
.todos {
display: grid;
grid-template-columns: 1fr 1fr;
}
.todo {
border: 1px solid #ccc;
}
.todo.undone {
grid-column: 2 /span 1;
}
.todo.done {
grid-column: 1 /span 1;
background: blue;
color: white;
}
.first-right {
grid-row-start: 1;
}
.flip-list-move {
transition: all 1s ease-in-out;
}
.header-wrapper {
display: grid;
grid-auto-flow: column;
}
.header, .todo {
display: grid;
grid-template-columns: repeat(3, 1fr);
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="header-wrapper">
<div class="header">
<span>Name</span>
<span>Age</span>
<span>Gender</span>
</div>
<div class="header">
<span>Name</span>
<span>Age</span>
<span>Gender</span>
</div>
</div>
<transition-group name="flip-list" tag="div" class="todos">
<div class="todo done" v-for="item of done" :key="item.id" #click="toggle(item)">
<span>{{item.name}}</span>
<span>26</span>
<span>Male</span>
</div>
<div :class="['todo', 'undone', { 'first-right': index === 0 }]" v-for="(item, index) of undone" :key="item.id" #click="toggle(item)">
<span>{{item.name}}</span>
<span>20</span>
<span>Male</span>
</div>
</transition-group>
</div>
Adding grid-row-start to the first undone element doesn't works if there are more than 6 items in array.
As a solution, I used the index of v-for loop to add to every undone todo the corresponding grid-row-start.
index starts at 0 so we have to make index + 1
<div
class="todo undone"
v-for="(item, index) of undone"
:key="item.id"
:style="{'grid-row': index + 1}" // => HERE we guarantee no gaps are present in undone list`
#click="toggle(item)"
>
<span>{{item.name}}</span>
<span>20</span>
<span>Male</span>
</div>
You can find the working example on this codesandbox

#click on parent div not firing when pressing child button

I have made a custom number input box component and want it to activate on click. The component consists of 3 elements, two buttons (for decreasing and increasing the number value), and an input, where the number is displayed and can manually be changed. The problem is that the #click of the parent div (.numberField) only fires when clicking the input box, not when the buttons are clicked.
Because the input box seemed to be working I have tried changing the button elements to input[type=button] elements, but that failed.
I have checked when #click of the child elements (the two buttons and the input) fire, and confirmed that all of them behave in the same way (they don't fire on the initial click that sets :disabled="false" on each of them)
My Vue version is 3.7.0 if that matters
<template>
<div class="numberField" #click="fieldClicked">
<button #click="stepDown()" :disabled="disabled" class="left">
−
</button>
<input
v-model="value"
type="number"
:max="max"
:min="min"
:step="step"
:disabled="disabled">
<button #click="stepUp()" :disabled="disabled" class="right">
&plus;
</button>
</div>
</template>
<script>
export default {
name: 'NumberField',
props: {
defaultValue: Number,
max: Number,
min: Number,
step: Number,
disabled: Boolean,
},
data() {
return {
value: this.defaultValue,
};
},
watch: {
value() {
this.value = Math.min(this.max, Math.max(this.min, this.value));
},
},
methods: {
stepDown() {
this.value -= this.step;
},
stepUp() {
this.value += this.step;
},
fieldClicked(event) {
// #click.stop will stop all clicks from propagating; we will only stop clicks when the field is active
if (!this.disabled) event.stopPropagation()
},
},
};
</script>
<style scoped>
.numberField {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 3em;
width: 8em;
}
.left {
border-top-left-radius: 0.2em;
border-bottom-left-radius: 0.2em;
}
.right {
border-top-right-radius: 0.2em;
border-bottom-right-radius: 0.2em;
}
input, button {
padding: 0;
border-radius: 0;
min-width: 0;
height: 100%;
width: 33%;
min-height: 0;
font-size: 1rem;
text-align: center;
}
</style>
This is a summary of how I'm using this component:
<div class="item" v-for="item in items" :key="item.id" #click="toggleItem(item.id)" :class="{ active: activeItems[item.id] }">
<h1>{{ item.name }}, some other elements irrelevant are here too</h1>
<NumberField
:defaultValue="item.amount"
:max="item.amount"
:min="1"
:step="1"
:disabled="!activeItems[item.id]"></NumberField>
</div>
toggleItem(id) toggles the boolean value of activeItems[item.id]. The NumberField is disabled when the item is inactive.
My expectation would be that clicking on any of the child elements of .numberField would fire the #click of .numberField, which (only if the item is inactive) then gets propagated to the #click of .item, but this only seems to be the case when clicking the input[type=number].
I would appreciate any help, I'm absolutely lost!
A <button> with a disabled attribute set will not fire click events. If the event doesn't fire on the <button> then it won't propagate to the <div> either.
In your case a simple workaround would be to put pointer-events: none on your buttons so that the button is skipped altogether. The <div> will just receive the click directly, as though the button wasn't even there.
const NumberField = {
name: 'NumberField',
template: `
<div class="numberField" #click="fieldClicked">
<button #click="stepDown()" :disabled="disabled" class="left">
−
</button>
<input
v-model="value"
type="number"
:max="max"
:min="min"
:step="step"
:disabled="disabled">
<button #click="stepUp()" :disabled="disabled" class="right">
&plus;
</button>
</div>
`,
props: {
defaultValue: Number,
max: Number,
min: Number,
step: Number,
disabled: Boolean,
},
data() {
return {
value: this.defaultValue,
};
},
watch: {
value() {
this.value = Math.min(this.max, Math.max(this.min, this.value));
},
},
methods: {
stepDown() {
this.value -= this.step;
},
stepUp() {
this.value += this.step;
},
fieldClicked(event) {
console.log('here')
// #click.stop will stop all clicks from propagating; we will only stop clicks when the field is active
if (!this.disabled) event.stopPropagation()
},
},
};
new Vue({
el: '#app',
components: {
NumberField
}
})
.numberField {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 3em;
width: 8em;
}
.left {
border-top-left-radius: 0.2em;
border-bottom-left-radius: 0.2em;
}
.right {
border-top-right-radius: 0.2em;
border-bottom-right-radius: 0.2em;
}
input, button {
padding: 0;
border-radius: 0;
min-width: 0;
height: 100%;
width: 33%;
min-height: 0;
font-size: 1rem;
text-align: center;
}
button[disabled] {
pointer-events: none;
}
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<number-field :defaultValue="7" :step="1" :min="0" :max="10" disabled></number-field>
</div>

Vue Accordion with transition

I'm trying to integrate the Accordion component with a body transition, but without success :( . All is working as well except the animation.
template:
<div class="accordion">
<div class="accordion-title" #click="isOpen = !isOpen" :class="{'is-open': isOpen}">
<span>{{title}}</span>
<i class="ic ic-next"></i>
</div>
<div class="accordion-body" :class="{'is-open': isOpen}">
<div class="card">
<slot name="body"></slot>
</div>
</div>
</div>
component:
props: {
title: {
type: String,
default: 'Title'
}
},
data() {
return {
isOpen: false
}
}
And styles:
.accordion-body {
font-size: 1.3rem;
padding: 0 16px;
transition: .3s cubic-bezier(.25,.8,.5,1);
&:not(.is-open) {
display: none;
height: 0;
overflow: hidden;
}
&.is-open {
height: auto;
// display: block;
padding: 16px;
}
}
.card {
height: auto;
}
I tried to use <transition> but it doesn't work with height or display properties.
Help please!
display:none will remove your content and avoid the animation, you should trick with opacity, overflow:hidden and height, but you ll be forced to do a method for that.
For example (not tested, but inspiring):
in template:
<div class="accordion" #click="switchAccordion" :class="{'is-open': isOpen}">
<div class="accordion-title">
<span>{{title}}</span>
<i class="ic ic-next"></i>
</div>
<div class="accordion-body">
<p></p>
</div>
</div>
in component (add a method):
methods: {
switchAccordion: function (event) {
let el = event.target
this.isOpen = !this.isOpen // switch data isOpen
if(this.isOpen) {
let childEl1 = el.childNodes[1]
el.style.height = childEl1.style.height
} else {
let childEl2 = el.childNodes[2]
el.style.height = childE2.style.height // or .clientHeight + "px"
}
}
}
in style:
.accordion {
transition: all .3s cubic-bezier(.25,.8,.5,1);
}
.accordion-body {
font-size: 1.3rem;
padding: 0 16px;
opacity:0
}
.is-open .accordion-body {
opacity:0
}
In this case, your transition should work as you want.
The javascript will change the height value and transition transition: all .3s cubic-bezier(.25,.8,.5,1); will do the animation