Reputation: 5168
I'm building an App using VueJS and Laravel.
TLDR;
includes function in VueJS is not giving the same output as it does in Javascript. It is splitting values within an array by the dash. Is there a way to prevent this?
Set up
I have a JSON with a list of languages, including their key and value. For example:
{"en":"English","en-au":"English (Australia)"}
I import this list and then push it into the data
as the value languages
Then in order to separate the list of languages that are already selected, I have a hidden input that has an array of these pre-selected languages:
<input type="hidden" value="['en-ca', 'pt']" name="used_languages" id="used_languages">
Then, just to test, I am putting them through a foreach loop:
<li v-for="(value, key) in languages" v-if="used_languages.includes(key)">@{{ value }}</li>
Problem
However, what is odd is that for this example, the following languages appear on the front end:
Note that I only have Canadian English and Portuguese in the array of values for used_languages.
It looks like includes is splitting en-ca by the dash and seeing if either en or ca are in the list and then taking these as well as en-ca as a whole.
This is not the expected behaviour.
Desired Behaviour:
To check the documentation, it should be like this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
It should only filter out Canadian English and Portuguese.
Question
Does anyone know why this is happening and how can I fix it?
All comments and questions are welcome!
Thanks a lot!
Thanks @SteveArcher for the massive help! To make Steve's point clear in terms of my example, what I had to do was:
Old:
<input type="hidden" value="['en-ca', 'pt']" name="used_languages" id="used_languages">
New:
<input type="hidden" value="en-ca,pt" name="used_languages" id="used_languages">
Notice that there are no spaces in there. That is important.
Old:
this.used_languages = doc.getElementById('used_languages').value
New:
this.used_languages = doc.getElementById('used_languages').value.split(',')
Thanks again Steve!
Upvotes: 0
Views: 277
Reputation: 641
You're running .includes
on the string "['en-ca', 'pt']"
, not the array ['en-ca', 'pt']
as you're expecting. For a string, includes will match any substring, (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes ), so that's why it's matching "en"
"en-ca"
"ca"
and "pt"
. Convert that string back into an array before calling .includes
and you'll be golden!
Upvotes: 1