Why cant I add two methods to a class using v-bind - vue.js

Using vue.js 2 I need to dynamically add classes to a <tr> element.
What works (single method call)
:tbody-tr-class="urgentEnquiryMixin_rowColour"
What doesn't work (two method calls, one a mixin)
Adding an additional method to the v-bind
:tbody-tr-class="urgentEnquiryMixin_rowColour applyUnreadClass"
What i have tried
:tbody-tr-class="[applyUnreadClass, urgentEnquiryMixin_rowColour]"
:tbody-tr-class="{applyUnreadClass(), urgentEnquiryMixin_rowColour}"
Additional code for info
applyUnreadClass(item, type) {
if (!item || type !== 'row') {
return '';
}
if (item.read === false) {
return 'unread-email-row';
}
return '';
}
urgentEnquiryMixin_rowColour(item, type) {
if (!item || type !== 'row') { return ''; }
if (item.isUrgent === true) { return 'tr-urgent'; }
return '';
}
<b-table id="assigned-enquiries-table" class="index-grid" headVariant="light" hover
:items="enquiriesData" :fields="columns" :current-page="page" :per-page="rowsPerPage"
show-empty :tbody-tr-class="applyUnreadClass, urgentEnquiryMixin_rowColour"
#filtered="onFiltered" :busy="isBusy"
>
Errors
'v-bind' directives require an attribute value
Parsing error: Unexpected token ','.
Parsing error: Unexpected token ','.eslint-plugin-vue

You can use class directly for optional classes.
You can even use class as well to have classes that always work:
<div
class="static"
:class="{ active: isActive, 'text-danger': hasError }"
></div>
So create props for these classes (which are booleans) and pass them like that to you.
However if you want to add them dynamically. Create ONE string that you paste inside class. This will contain all classes in that string. (eg. 'Class1 Class2 Class3')
https://v2.vuejs.org/v2/guide/class-and-style.html

Related

Computed property not disabling input

I am trying to set the disabled property on a text field via checkbox. I'm referencing this item, but none of the solutions are working for me.
My text field and checkbox are as follows:
<input
type="checkbox"
class="form-check-input"
v-model="formData.useSystemSetting"
>
<input
type="text"
class="form-control"
:class="hasError('maxCount') ? 'is-invalid' : ''"
placeholder="Enter the Maximum Count"
v-model="formData.maxCount"
:disabled = "isDisabled"
>
My computed property is:
computed:{
isDisabled: function() {
this.useSystemSetting = this.useSystemSetting == true?false:true
return this.useSystemSetting;
},
I'm also setting useSystemSettings in the data section to true because if I don't it doesn't get populated. When I add a breakpoint to the computed property, it's only getting hit on the page load, but not after.
It's not allowed to mutate other properties inside the computed property, you should only do some process and return a value:
computed:{
isDisabled: function() {
return this.useSystemSetting ? false : true;
}
}
You shouldn't mutate data inside a computed property.
A computed property is used whenever you need to use logic for getting a value which includes reactive data, as you'd find here.
You could try something like:
computed:{
isDisabled: function() {
return !this.formData.useSystemSetting;
}
}
Presuming that the formData object will not be null at this point.
To prevent that, you could also use something like:
return ((this.formData || {}).useSystemSetting || true) ? false : true;

Vue - set v-model dynamically (with a variable containing a string)

I haven't been able to set v-model dynamically.
It works if I type explicitly:
<div class="form-group mr-3 mb-2">
<input type="text"
v-model="form[filters][firstlastname]"
>
</div>
But I want to loop through an object wherein I have string , like: 'form[filters][firstlastname]'
The parent has the form with properties:
data() {
return {
form: new Form({
filters: {
gender: [],
firstlastname: 'My firstlastname'
So, from the parent I pass down the form and filters into the child component, here is filters:
let formFilters = { filters: [
{
type: 'text',
property: 'form[filters][firstlastname]', // <-- string
placeholder: 'Name',
},
{
type: 'number',
property: 'paginate',
placeholder: 'Max rows'
},
]
}
Child component: (here I loop through the object and generate the input fields)
<div v-for="(filter,index) in formFilters.filters"
:key="`${index}_${filter.property}`"
>
<input
v-if="filter.type === 'text' || filter.type === 'number'"
:placeholder="filter.placeholder"
:type="filter.type"
v-model="filter.property" //<--- set the property
>
This doesn't work. The v-model just interprets it as a string and not a reference to a form property.
I tested other ways, like: v-model="``${[filter.property]}``" (single, not double ```` but it wont show in stackoverflow otherwise) and other crazy things but it isn't valid.
So how do I set v-model with a variable containing a string (so that it can be set dynamically)?
This is a very tricky problem....
You can access any property present in the data inside html template using 2 ways,
Referring to the property directly
Using $data
data() {
return {
firstlastname: 'Mr First last name'
}
}
so, in html template you can use either
<p>{{firstlastname}}</p>
or
<p>{{$data.firstlastname}}</p>
For your scenario $data can be used for primitive data types like string or number,
<input
v-if="filter.type === 'text' || filter.type === 'number'"
:placeholder="filter.placeholder"
:type="filter.type"
v-model="$data[filter.property]">
But this will not work for your second scenario where you are trying to access nested property of an object form.filters.firstlastname
You can access this property using the following notation $data[form][filters][firstlastname]
In your case, the for loop will result as $data[form.filters.firstlastname] or $data[[form][filters][firstlastname]] which will throw an exception
As suggested in the comments, try different approach or flatten the object. You can refer to this link to see how to flatten the object https://stackoverflow.com/a/25370536/2079271

vuetify rule function - how to access component label during validation?

I would like to access the label property of a component in it's "Rules" function so I can return an (already) localized field name in the error message.
Is there any way to access the properties of the component in the rule function that's called by Vuetify for validation?
<v-text-field
v-model="obj.count"
:counter="10"
:label="this.$locale.get('WidgetCount')"
:rules="MyRuleFunctionInMyRuleLibrary()"
name="count"
required
></v-text-field>
As can be seen in the code I have a function to localize the field label already, I don't want to re-do it twice or have to specify it twice. In "MyRuleFuctionInMyRuleLibrary" I want to validate the rule and report on it localized properly.
I know I can just pass the localized text Key in my rule function but that would create a redundancy as I would have to type it twice in the template and I also need some other properties of the control / component so I would rather pass or have access to the component itself. I already tried passing "this" to the component, e.g.:
:rules="MyRuleFunctionInMyRuleLibrary(this, obj.count)"
However this in this case appears to be everything on the page / form, not the single component itself.
Using typescript:
<v-text-field v-model="volume.sizePerInstance" :rules="sizePerInstanceRules" :label="$t('volumes.sizePerInstance') + ' (GB)'" type="number" step="0.01" required min="0" color="#0cc2aa"></v-text-field>
You have to define a getter in order to get acces to component properties:
get sizePerInstanceRules() {
return [
(v: number) => v && v > 0 || 'Max size must be greater than 0',
(v: any) => v && !isNaN(v) || 'Max size must be a number',
(v: number) => {
return this.maxValue >= v || 'Exceeded limit';
},
];
}
In Vuetify source code, rules function has only 1 parameter (value). You can work around by define label as data or computed property:
<v-text-field
v-model="obj.count"
:counter="10"
:label="label.count"
:rules="MyRuleFunctionInMyRuleLibrary()"
name="count"
required
></v-text-field>
Add label to data
data: () => ({
label: {
count: this.$locale.get('WidgetCount')
}
})
then you can access localize label in validation function by this.label.count
You might want to watch locale change to change label manually:
watch: {
locale: function () {
this.label = {
count: this.$locale.get('WidgetCount')
}
}
}

Set a variable inside a v-for loop on Vue JS

I have a v-for loop with vue.js on a SPA and I wonder if it's posible to set a variable at the beginning and then just print it everytime you need it, because right now i'm calling a method everytime i need to print the variable.
This is the JSON data.
{
"likes": ["famiglia", "ridere", "caffè", "cioccolato", "tres leches", "ballare", "cinema"],
"dislikes":["tristezze", "abuso su animali", "ingiustizie", "bugie"]
}
Then I use it in a loop:
<template>
<div class="c-interests__item" v-for="(value, key) in interests" :key="key" :data-key="key" :data-is="getEmotion(key)" >
// NOTE: I need to use the variable like this in different places, and I find myself calling getEmotion(key) everythime, is this the way to go on Vue? or there is another way to set a var and just call it where we need it?
<div :class="['c-card__frontTopBox', 'c-card__frontTopBox--' + getEmotion(key)]" ...
<svgicon :icon="getEmotion(key) ...
</div>
</template>
<script>
import interests from '../assets/json/interests.json'
... More imports
let emotion = ''
export default {
name: 'CInfographicsInterests',
components: {
JSubtitle, svgicon
},
data () {
return {
interests,
emotion
}
},
methods: {
getEmotion (key) {
let emotion = (key === 0) ? 'happy' : 'sad'
return emotion
}
}
}
</script>
// Not relevanty to the question
<style lang='scss'>
.c-interests{...}
</style>
I tried adding a prop like :testy="getEmotion(key)" and then { testy } with no luck...
I tried printing { emotion } directly and it doesn't work
So, there is anyway to acomplish this or should i stick calling the method every time?
Thanks in advance for any help.
It's not a good idea to use methods inside a template for non-user-directed actions (like onClicks). It's especially bad, when it comes to performance, inside loops.
Instead of using a method, you can use a computed variable to store the state like so
computed: {
emotions() {
return this.interests.map((index, key) => key === 0 ? 'happy' : 'sad');
}
}
This will create an array that will return the data you need, so you can use
<div class="c-interests__item"
v-for="(value, key) in interests"
:key="key" />`
which will reduce the amount of times the item gets re-drawn.

access object with dynamic variable vue.js

This is my object
var users ={
twitter : {
name : //,
lastname : //
},
facebook : {
name : //,
lastname : //
}
}
}
I have a dynamic variable activeuser that updates from Facebook to twitter.
What i'm trying to do is refer to the inner object in users depending on the value of activeuser. I need to give my div something like this class :
<div class=' {{users.activeuser}}'></div>
I know this is not how it should be done with vue.js. Do you have any suggestions?
Thank You!
Using VueJS you should be able to assign your dynamic variable to a Vue Model when you load the new object using a Vue setter $set('property name', 'value')
Example AJAX retreival:
$.getJSON('myURL.html?query=xxx', function(data, textStatus, jqXHR){
try{
MyVue.$set('dynamicObject', data);
}
catch(e){}
});
A generic Vue may look like this:
var MyVue = new Vue({
el:'#exampleDiv',
data: {
dynamicObject : ''
}
});
Bound to an example HTML element:
<div id="exampleDiv">
<label class="{{dynamicObject.activeuser}}">{{dynamicObject.username}}</label>
</div>
In the case that you have an object with an array of objects which also contain properties Vue makes it very simple to create many HTML elements (for each child object) by simply adding a v-repeat (example) to the desired HTML and assigning the datasource:
<div id="exampleDiv">
<label v-repeat="dynamicObject" class="{{dynamicObject.activeuser}}"></label>
</div>