Vuejs Computed Property warns that I have no setter - vuejs2

I have a code like this:
<button
#click="addFieldRow"
:disabled="disableAddRow"
>
disableAddRow is a computed property like this:
disableAddRow() {
if (this.currentIndex !== null) {
return !this.fieldList[this.currentIndex].filterApplied;
}
if (this.currentIndex === null && this.fieldList.length === 1) {
return true;
}
return false;
}
Works as it should, but on my console log, I get the following warning:
[Vue warn]: Computed property "disableAddRow" was assigned to but it
has no setter.
I don't get why I need a setter? And if I do need a setter, I don't understand what I need to set...
Thank you for your time and help!

That warning is indicating that, somewhere in your code, you are assigning a value to your disableAddRow computed property.
The code you shared wouldn't cause that warning, so you must be inadvertently assigning it a value somewhere else. You simply need to not set the value of the computed property and you won't get that warning anymore.
For a little more context: computed properties, by default, retrieve the value returned by the defining function. It is, however, possible to define setters for computed properties as well (which is what the warning is alluding to).

Related

Is Mutating a Data copy of a Prop object any better than mutating a prop? Why?

In the Vue docs there is a section on one-way data flow: https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
Here it explains that you should not mutate a prop. Additionally, it says:
The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case, it’s best to define a local data property that uses the prop as its initial value:
At the bottom of this section, there is a note that says:
Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect parent state.
I’m considering the situation where you have a prop that is an object (or an array) and you have defined a local data property that uses the prop as its initial value:
props: {
initialMyObject: {
type: Object,
required: true
}
},
data() {
return {
myObject: this.initialMyObject
}
}
If I mutate the data item myObject, since it is an object the prop itself will end up getting mutated. Is this therefore the same essentially as “mutating a prop” and to be avoided? Would it be preferable in this case to emit an event whenever a change to the object is desired (or to use Vuex)?
Thanks in advance for your help on this.
You can simply clone it though -
data() {
return {
myObject: {...this.initialMyObject}
}
}
To avoid it.
But yeah you just can't reassign a value to a prop as
It's just because Object is kind of reference memory. When you have Array or Object stored in any variable it's a reference variable.
Memory management in such case, The reference variable will points to a memory address in heap so you can add more n more value to address. However you cannot just replace that address with any new value even with the new address.
In my preference, You should prefer Vuex, whenever you want a value to get updated for whole project

How to use a computed property and Vuex, without getting reactivity errors

I would like to understand when you can use a computed property like this:
computed: {
selectedDate () {
return this.$store.getters['stockProposal/getDateEndArticle']
}
}
Where the getter is defined as follows:
getDateEndArticle: state => {
return state.articleSettings['date_end']
}
Where in the template I then use:
v-model="selectedDate"
Sometimes this works for me, but often I get the following error 'Property or method "selectedDate" is not defined on the instance but referenced during render.'
Can someone explain to me why this is not always working?
I also tried to follow this tutorial: https://itnext.io/anyway-this-is-how-to-use-v-model-with-vuex-computed-setter-in-action-320eb682c976. But even with a computed setter added, I still get the same error. While I am doing exactly this: https://vuex.vuejs.org/guide/forms.html#two-way-computed-property.

What exactly does computed properties in vuejs?

There are couple of questions related computed properties like the following
"vuejs form computed property"
"Computed properties in VueJs"
"computed property in VueJS"
"Use computed property in data in Vuejs"
They are asking about specific error or logic. There are lot of websites that are explaining about vuejs related concepts. I read about computed properties on vuejs official website. When we do complex calculations or want to avoid to write more logic in our html template then we use computed properties.
But could not get any solid understanding about computed properties, when it calls, how it calls, what exactly do?
TL;DR: Computed properties are getters/setters in Vue.
When defined in the shorthand form, they are getters:
computed: {
someComputed() {
return `${this.foo} ${this.bar}`;
}
}
is equivalent with
computed: {
someComputed: {
get: function() {
return `${this.foo} ${this.bar}`;
}
}
}
which can also have a setter:
computed: {
someComputed: {
get: function() {
return `${this.foo} ${this.bar}`;
}
set: function(fooBar) {
const fooBarArr = fooBar.split(' ');
this.foo = fooBarArr[0];
this.bar = fooBarArr[1];
}
}
}
In short, Vue computed properties allow you to bind an instance property to
a getter: function run when you look up that property; usage:
this.someComputed // returns the computed current value, running the getter.
a setter: function run when you attempt to assign that property; usage:
this.someComputed = value; // sets the computed current value, running the setter.
Read more on getters and setters in Javascript.
And here's the documentation on Vue computed properties.
You can use computed properties when for example you have some logic what will blow up your template.
The idea is, that normally you want to keep all javascript logic in the javascript side of your vue component, and only access final data in your data (if possible)
For that you can use computed props, which normally are doing simple things like:
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
Or an another good example if you have some currency and you want to format it with thousand separator and euro ign at the end.
Then you can access your computed prop in the template like you access a normal prop, you dont have to call it as a function.
like so:
<div>{{reversedMesage}}</div>
Every time, when any variable what is used in your conputed prop is changing, vue vill take care of it and will re-calculate your computed property again.
Lets say you have the following:
computed: {
prettyAmount: function () {
return this.amount + ' ' + this.currency.toUpperCase()
}
}
<div>{{prettyAmount}}</div>
Whenever currency or amount changes, the output of prettyAmount will be changed as well.

Simple Vue.js Computed Properties Clarification

I'm not new to Vue.js, but I'm going through the docs again, trying to pick up on anything I missed the first time. I came across this statement in basic example section of using computed properties:
You can data-bind to computed properties in templates just like a normal property. Vue is aware that vm.reversedMessage depends on vm.message, so it will update any bindings that depend on vm.reversedMessage when vm.message changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function has no side effects, which makes it easier to test and understand.
The part about we’ve created this dependency relationship declaratively: the computed getter function has no side effects, isn't clear to me. I do understand that a side effect is some action happening that is not directly related to the pure intentions of the function, but I'm not clear how it's being used in this statement.
Could someone explain further what the opposite could be? What are the potential side effects that could be happening?
The term side effect here refers to any data mutations performed in the computed property getter. For example:
export default {
data() {
return {
firstName: 'john',
lastName: 'doe',
array: [1,2,3]
}
},
computed: {
fullName() {
this.firstName = 'jane'; // SIDE EFFECT - mutates a data property
return `${this.firstName} ${this.lastName}`
},
reversedArray() {
return this.array.reverse(); // SIDE EFFECT - mutates a data property
}
}
}
Notice how fullName mutates firstName, and reversedArray mutates array. If using ESLint (e.g., from Vue CLI generated project), you'd see a warning:
[eslint] Unexpected side effect in "fullName" computed property. (vue/no-side-effects-in-computed-properties)
[eslint] Unexpected side effect in "reversedArray" computed property. (vue/no-side-effects-in-computed-properties)
demo

Setter is invoked before constructor

I am trying to create instances of class HelloWorld, however it does not work. I found that problem is that setter methods called instead of constructor which should initialize variable name, while variable welcome is optional.
I specified getters and setters for both variables. Browser's console is throwing an error about maximum call stack size. If I comment my getters&setters it stops throwing errors.
Could anyone explain me that strange behaviour?
Also there is another problem with mapping. I'm trying to "return" an array if li elements like in React by using .map(). It gives me the result with commas. How can I get rid of them while printing?
This is a link to my code https://codepen.io/CrUsH20/pen/yzMjzL?editors=1010
Updated #1
I fixed the problem with getters&setters by giving a _ sign for private values.
Now I have a problem with
function print() {
if (invitations) {
document.getElementById('result').innerHTML = invitations.map((e)=> {
return `<li>${e.welcome + e.name}</li>`;
});
}
}
Compiler complains that Type 'string[]' is not assignable to type 'string'. in document.getElementById('result').innerHTML while type was not assigned since it is a html element
Update #2
There are solutions:
1# About conflict with constructor and set&get - I changed object's values by adding to their names _. It solved the conflicts.
2# About commas - I added after map .join('') which solved my problem.
The following code (subset of yours) is a compile error:
class HelloWorld {
constructor(public name: string) {
}
set name(e: string) {
this.name = e;
}
get name(): string {
return this.name;
}
}
Garbage in => Garbage out
Fix
Dont use getter / setters and properties with the same name.