Vue JS pass a value inside to a CSS property - vue.js

I'm developing an exams portal application.
and this is my code.
<div class="" v-for="areas in knowledgeAreas">
{{areas.area}}<div class="progress" style="margin-top:10px;">
<div class="progress-bar" style="width:50%">{{areas.correctlyMarkedAnswers}} out of {{areas.numberOfQuestion}}</div>
</div>
</div>
and
data(){
return{
knowledgeAreas :[
{ area: 'Math',numberOfQuestion:10,correctlyMarkedAnswers:3,correctAnswersPercentage:12 },
{ area: 'IQ',numberOfQuestion:10,correctlyMarkedAnswers:5,correctAnswersPercentage:5 },
{ area: 'GK',numberOfQuestion:10,correctlyMarkedAnswers:8,correctAnswersPercentage:3 }
]
}
}
What I want is to dynamically pass the correctAnswersPercentage property's value to the CSS width property.

I created getProgress method then pass the value of correctAnswersPercentage during iteration.
Please check the snippet below:
new Vue({
el: "#app",
data: {
knowledgeAreas :[
{ area: 'Math',numberOfQuestion:10,correctlyMarkedAnswers:3,correctAnswersPercentage:50 },
{ area: 'IQ',numberOfQuestion:10,correctlyMarkedAnswers:5,correctAnswersPercentage:60 },
{ area: 'GK',numberOfQuestion:10,correctlyMarkedAnswers:8,correctAnswersPercentage:70 }
]
},
methods: {
getProgress: function(width) {
return {
'width': width + '%',
'background-color': 'yellow'
};
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<div id="app">
<div class="" v-for="areas in knowledgeAreas">
{{areas.area}}<div class="progress" style="margin-top:10px;">
<div class="progress-bar" v-bind:style="getProgress(areas.correctAnswersPercentage)">{{areas.correctlyMarkedAnswers}} out of {{areas.numberOfQuestion}}</div>
</div>
</div>
</div>

Related

How can I select element Id with a function in Vue.js?

I want to use the Id of the element in which I use the function as a parameter. Example:
<div
class="col-2 column-center"
id="myId"
#mouseover="aFunction(id)"
>
methods: {
aFunction(id){
alert(id);
}
}
But it doesn't work. How can I do it?
In another way, you can make your id attribute bind with the data property, like this :
<template>
<div class="col-2 column-center" v-bind:id="id" #mouseover="aFunction(id)">
test
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
id: 'myId',
};
},
methods: {
aFunction(id) {
alert(id);
},
},
};
</script>
You can pass the event to the method and then get the id from event.target.id.
https://jsfiddle.net/tr0f2jpw/
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
aFunction(event){
alert(event.target.id);
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div
class="col-2 column-center"
id="myId"
#mouseover="aFunction($event)"
>
some stuff
</div>
</div>

Vue resets child Component data on props update

I have child component, that has some internal data, that should not be changed from outside. But when I update prop from parent component, this internal data is reset.
Basically in example below, when we change title from outside, value is set back to empty ''. How can I make value persistent with Child component props update?
Child.vue
<template>
<div class="child">
<h2>{{title}}</h2>
<input type="text" :value="value" v-on:change="$emit('change', $event.target.value)">
</div>
</template>
<script>
export default {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
}
}
</script>
Parent.vue
<template>
<div class="parent">
<Child :title="title" v-on:change="processTitle($event)"></Child>
</div>
</template>
<script>
import Child from './Child';
export default {
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.reverse();
}
}
}
</script>
You are not setting the value data attribute, :value=value means that "if value changes, the input value should pick up that change". But value doesn't change. Use v-model instead if you want to keep it simple.
Vue.component("Child", {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
},
template: `
<div class="child">
<h2>{{title}}</h2>
<input type="text" v-model="value" v-on:change="$emit('change', $event.target.value)">
</div>
`
})
new Vue({
el: "#app",
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.split("").reverse().join("");
}
},
template: `
<div class="parent">
<child :title="title" v-on:change="processTitle($event)"></child>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
EDIT
Also, if you want a continuous effect, don't use #change - use #input instead:
Vue.component("Child", {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
},
template: `
<div class="child">
<h2>{{title}}</h2>
<input type="text" v-model="value" v-on:input="$emit('change', $event.target.value)">
</div>
`
})
new Vue({
el: "#app",
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.split("").reverse().join("");
}
},
template: `
<div class="parent">
<child :title="title" v-on:change="processTitle($event)"></child>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Button component does not receive DataTable props

I am trying to add a button to my vuejs DataTable. I created a Button component and I can add it as a column in my DataTable, but I can't send it through props. I do not have full knowledge of vue, for sure I am doing something wrong.
Vue.component('edit-button', {
template: `
<button class="btn btn-xs btn-primary" #click="goToUpdatePage">Edit</button>
`,
props: ['data'],
methods: {
goToUpdatePage: function(){
alert(data)
}
}
});
export default {
data() {
return {
numeroPagina: 1,
tiposNatureza: [],
utisMoveis: [],
list: [],
filtros: {
dataInicial: new Date().toISOString().split('T')[0],
dataFinal: new Date().toISOString().split('T')[0],
selectedUtisMoveis: [],
selectedStatus: [],
selectedTipoNatureza: [],
selectedTipoPesquisa: ''
},
tabela: {
columns: [
{
// <a data-toggle="modal" data-target="#ExemploModalCentralizado">${row.DESCRICAO}</a>
label: 'Descrição', representedAs: function (row) {
if (row.DESCRICAO) return `<a data-toggle="modal" data-target="#ExemploModalCentralizado">${row.DESCRICAO}</a> <button onclick="alertMe('TESTE')">TESTE</button>`
else return '<b>Sem informação</b>'
}, interpolate: true
},
{
label: 'Quantidade', representedAs: function (row) {
return `<p><span class="label label-primary" style="font-size: 17px">${row.QTD}</span></p>`
}, interpolate: true
},
{
label: 'Action',
component: 'edit-button',
data: 'row',
component_data: {
path: 'contact',
action: 'update'
}
}
],
rows: []
}
}
}
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h2 v-if="quantidadeDeRegistros > 0">Foram encontrado(s) {{ quantidadeDeRegistros }}
resultado(s)</h2>
</div>
<div class="ibox-content no-padding" style="font-size: 15px">
<datatable :columns="tabela.columns" :data="tabela.rows"></datatable>
<datatable-pager v-model="numeroPagina" type="abbreviated" :per-page="8"></datatable-pager>
</div>
</div>
</div>
</div>
I need to create a button that takes the information from the selected row (row.DESCRIPTION) and sends it to a method, where I will do some dealing in a modal. Thank you very much in advance.
Try using this to reference the component scope.
alert(this.data)
And remove:
props: ['data'],
You do not want a passed in prop called data. You want the component's defined data property

Set css class for single items in v-for loop

I am playing around with Vue.js and I am trying to change the class of individual items in a v-for route dependent on a checkbox.
<template>
<div>
<ul>
<div :class="{completed: done}" v-for="things in items">
<h6 v-bind:key="things"> {{things}} - <input #click="stateChange" type="checkbox"/></h6>
</div>
</ul>
</div>
</template>
<script>
export default {
name: 'ItemList',
data() {
return {
items: [],
done: false
}
},
mounted() {
Event.$on('itemAdded', (data) => {
this.items.push(data);
})
},
methods: {
stateChange() {
this.done = !this.done;
}
}
}
</script>
<style>
.completed {
text-decoration-line: line-through;
}
</style>
The above code places a line through every item, not just the checked one.
How do I code so only the checked item is crossed out?
Thanks
Paul.
It looks like you have only one done property. You should have a done property for each element in your items array for this to work. Your item should like {data: 'somedata', done: false }
This should work:
<template>
<div>
<ul>
<div :class="{completed: item.done}" v-for="(item,index) in items">
<h6 v-bind:key="things"> {{item.data}} - <input #click="stateChange(item)" type="checkbox"/></h6>
</div>
</ul>
</div>
</template>
<script>
export default {
name: 'ItemList',
data() {
return {
items: [],
}
},
mounted() {
Event.$on('itemAdded', (data) => {
this.items.push({ data, done: false });
})
},
methods: {
stateChange(changeIndex) {
this.items = this.items.map((item, index) => {
if (index === changeIndex) {
return {
data: item.data,
done: !item.done,
};
}
return item;
});
}
}
}
</script>
<style>
.completed {
text-decoration-line: line-through;
}
</style>
#Axnyff
You were very close. Thank you. Here is the little changes I made to get it working.
<template>
<div>
<ul>
<div :class="{completed: item.done}" v-for="item in items">
<h6> {{item.data}} - <input #click="item.done = !item.done" type="checkbox"/></h6>
</div>
</ul>
</div>
</template>
<script>
export default {
name: 'ItemList',
data() {
return {
items: [],
}
},
mounted() {
Event.$on('itemAdded', (data) => {
this.items.push({ data, done: false });
console.log("DATA- ", this.items)
})
},
methods: {
}
}
</script>
<style>
.completed {
text-decoration-line: line-through;
}
</style>

Vue do not save clicked element style

I am generating small list of items. After click on every single item it should change style. Only one item can be selected. If you click on another item first item reverse to default value.
I have follow code:
<div class="LngList">
<div class="lng" v-for="item in languages">
<button :class="[ isLangSelected ? 'ui inverted basic button' : 'ui inverted red basic button' ]" #click=LangSelect(item.lang)>{{item.lang}}</button>
</div>
</div>
My method:
data: function (){
return {
isLangSelected: false,
mycode: "",
languages: [
{lang:'D'},
{lang:'C#'},
{lang:'Python'}
],
selectedLanguage: ""
}
},
methods: {
LangSelect(lang)
{
this.selectedLanguage = lang;
if(this.selectedLanguage.length != "")
{
this.isLangSelected = !this.isLangSelected;
}
}
}
But when I am clicking outside the button I am losing selected style.
I did small gif to show the problem:
This is possible of course with buttons, but why don't you use a radio input instead? Having only one item selected, that's what they are done for.
new Vue({
el: '#app',
data() {
return {
languages: [{
lang: 'D'
},
{
lang: 'C#'
},
{
lang: 'Python'
}
],
selectedLanguage: ''
};
},
computed: {
isLangSelected() {
return this.selectedLanguage !== '';
}
}
});
input[type=radio] {
visibility: hidden;
width: 0;
}
input[type=radio]:checked + span {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<label v-for="lang in languages">
<input type="radio" name="languages"
v-model="selectedLanguage" :value="lang.lang">
<span>{{lang.lang}}</span>
</label>
<div v-if="isLangSelected">
Selected language is: {{ selectedLanguage }}
</div>
</div>