How to populate empty array with a method in Vue - vue.js

I'm trying to populate an empty array with a declared array variable in a computed function. I tried this but with no luck:
data: {
hashtags: []
},
computed: {
filteredHashtags () {
var defaultHashtags = [ '#hr', '#acc', '#sales' ];
var fHashtags =
_.chain( messages )
.pluck( 'hashtags' )
.flatten()
.map(
function ( tag ) {
return tag && tag.trim() ? '#' + tag : null; })
.filter( Boolean )
.value();
fHashtags = _.union( fHashtags, defaultHashtags );
return data.hashtags = fHashtags;
}
}
also, is there a better method to approach this?

A computed property isn't really a good use case for this, because the computed value has to be referenced in order for it to be called. Instead, just make it a method and call it the method when your Vue is created.
data: {
hashtags: []
},
methods: {
filterHashtags() {
// commented out stuff
// set the data property with the filtered values
this.hashtags = fHashtags;
}
},
created(){
this.filterHashtags();
}

Related

How to reference to element from state in foreach (Vuex)?

I am using vuex in my vue application. In store is a declared object:
state: {
list: {
a: false,
b: false,
c: false
}
}
In mutations is mutation that receives arrays in parameters, for example: el: ['a', 'b'].
Those elements in the el array must be set to true in list object in state. I'm using a foreach loop for this:
mutations: {
SET_LIST(state, el) {
el.forEach(element => {
if (state.list.element) {
state.list.element = true;
}
});
}
}
But I am getting an error: error 'element' is defined but never used.
Because element is not used and I don't know how to refer to it correctly.
I searched on the internet and found this solution: state.list[element]. I don't get an error then, but it doesn't work.
Use the bracket notation [] to get the property dynamically :
mutations: {
SET_LIST(state, el) {
el.forEach(element => {
if (Object.keys(state.list).includes(element)) {
state.list[element] = true;
}
});
}
}

Why Am I getting error return in computed property?

I'm using Vuex, inside Getter Foo function I'm returning two values inside array:
return ["Try Again"] or return ["Data result", data], in computed, I'm checking the array length and returning depending on result
computed:{
Foo: function(){
const getFoo = this.$store.getters.Foo;
if(getFoo.length === 1) {
this.existFoo = false
return getFoo[0]
}
this.existFoo = true
return getFoo
}
}
but I'm getting this error, even reading others posts I cannot solve it
34:9 error Unexpected side effect in "Foo" computed property
vue/no-side-effects-in-computed-properties
37:7 error Unexpected
side effect in "Foo" computed property
vue/no-side-effects-in-computed-properties
You are not permitted to change the state in computeds.
Try using another computed instead of existFoo
computed:{
Foo(){
if(this.$store.getters.Foo.length === 1) {
return this.$store.getters.Foo[0]
}
return this.$store.getters.Foo
},
existFoo(){
return this.$store.getters.Foo.length > 1
}
}
Now you should remove existFoo from state
You could use a watcher to watch the store value and set your local variables.
computed: {
getFooFromStore() {
return this.$store.getters.Foo
}
}
watch: {
getFooFromStore: function() {
this.existFoo = this.getFooFromStore[0] ? false : true;
}
}

How to filter array in json object with computed

fetchData() {
axios.get("api_url").then((response) => {
this.dataArr = response.data;
});
},
I can't do this.dataArr = response.data.items.fruits; because I need to use this somewhere else like this.
dataArr looks like this:
{
"items":{
"fruits":[
{
"name":"banana",
"type":"fruit",
},
{
"name":"kiwi",
"type":"fruit",
},
]
}
I am trying to filter this in computed property:
filterData(){
return this.dataArr.filter((item) => item.name )
}
But I am getting an error saying that this.dataArr is not a function, I need to get access to this.dataArr.items.fruits, but when I write it like that it's not working. Is there way to solve this?
You should get access to the nested fruits array and it seems that you're trying to map that array by returning only the names in this case use map method:
filterData(){
if(this.dataArr.items && this.dataArr.items.fruits){
return this.dataArr.items.fruits.map((item) => item.name )
}else{
return []
}
}

Vue: Watch array data variable doesnt work

i'm trying to watch an array declarated in data method (the 'validated' variable). I already have a watcher to an input (legal_name) and it works correctly but the array watcher doesnt give any response. Any idea?
export default {
data() {
return {
legal_name : '',
validated: [],
errors: []
}
},
watch: {
validated() {
console.log('modified')
},
legal_name(value) {
this.eventName();
this.legal_name = value;
this.checkLength(value, 3);
}
},
methods: {
checkLength(value, lengthRequired) {
if(value.length < lengthRequired) {
this.errors[name] = `Debes ingresar al menos ${lengthRequired} caracteres`;
this.validated[name] = false;
return false;
}
this.errors[name] = '';
this.validated[name] = true;
return true;
},
eventName() {
name = event.target.name;
}
}
}
You need to call Vue.set() for arrays, and NOT use indexing such as
foo[3]= 'bar'
Vue DOES recognize some operations, such as splice and push, however.
Read more about it here: https://vuejs.org/2016/02/06/common-gotchas/ and here: https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection
So for your code, and using the Vue handy helper method $set:
this.validated.$set(name, true);
Why...
Javascript does not offer a hook (overload) for the array index operator ([]), so Vue has no way of intercepting it. This is a limitation of Javascript, not Vue. Here's more on that: How would you overload the [] operator in javascript

Vuejs2 - computed property in components

I have a component to display names. I need to calculate number of letters for each name.
I added nameLength as computed property but vuejs doesn't determine this property in loop.
var listing = Vue.extend({
template: '#users-template',
data: function () {
return {
query: '',
list: [],
user: '',
}
},
computed: {
computedList: function () {
var vm = this;
return this.list.filter(function (item) {
return item.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1
})
},
nameLength: function () {
return this.length; //calculate length of current item
}
},
created: function () {
this.loadItems();
},
methods: {
loadItems: function () {
this.list = ['mike','arnold','tony']
},
}
});
http://jsfiddle.net/apokjqxx/22/
So result expected
mike-4
arnold-6
tony-4
it seems there is some misunderstanding about computed property.
I have created fork from you fiddle, it will work as you needed.
http://jsfiddle.net/6vhjq11v/5/
nameLength: function () {
return this.length; //calculate length of current item
}
in comment it shows that "calculate length of current item"
but js cant get the concept of current item
this.length
this will execute length on Vue component it self not on that value.
computed property work on other property of instance and return value.
but here you are not specifying anything to it and used this so it wont able to use any property.
if you need any more info please comment.