link1644 link1645 link1646 link1647 link1648 link1649 link1650 link1651 link1652 link1653 link1654 link1655 link1656 link1657 link1658 link1659 link1660 link1661 link1662 link1663 link1664 link1665 link1666 link1667 link1668 link1669 link1670 link1671 link1672 link1673 link1674 link1675 link1676 link1677 link1678 link1679 link1680 link1681 link1682 link1683 link1684 link1685 link1686 link1687 link1688 link1689 link1690 link1691 link1692 link1693 link1694 link1695 link1696 link1697 link1698 link1699 link1700 link1701 link1702 link1703 link1704 link1705 link1706 link1707 link1708 link1709 link1710 link1711 link1712 link1713 link1714 link1715 link1716 link1717 link1718 link1719 link1720 link1721 link1722 link1723 link1724 link1725 link1726 link1727 link1728 link1729 link1730 link1731 link1732 link1733 link1734 link1735 link1736 link1737 link1738 link1739 link1740 link1741 link1742 link1743 link1744 link1745 link1746 link1747 link1748 link1749 link1750 link1751 link1752 link1753 link1754 link1755 link1756 link1757 link1758 link1759 link1760 link1761 link1762 link1763 link1764 link1765 link1766 link1767 link1768 link1769 link1770 link1771 link1772 link1773 link1774 link1775 link1776 link1777 link1778 link1779 link1780

[Vue.js] How to work with local versions of data objects within a Vue.js application? Subscribe to RSS

I’m using Vue.js and vuex to work with data from a backend store that I access via and api.
My question may be more about semantics and how to actually ask this question and search for better answers because I don’t even know the correct terms to be searching on. So here goes…

Within my vue.js code I make a call to my back end api and it returns a json blob with a block of data that to work with in the ui. No problems there. But then I need to slightly modify that data to present it to the user. this entails assessing a few fields and changing them (say, if the value is 0 put in ‘n/a’, etc.), maybe doing some math on a few fields and so on. Then I present that to the user in a grid/table. the user to be able to sort and search on the fields as well. So I may display a field named fullName that comes from the back end but allow the user to sort on a field named lastName that is not actually in the grid.

With that said, here is my question - should I be creating a single ‘transformer/reducer’ in code to translate the data object coming from the api into what I need for the ui? Or should I be writing multiple filters (by this I mean Vue.js filters that go directly in the html with the ‘|’ pipe) to just modify the fields directly in the html template?
My concern is the once i modify the object coming back from the api what if there is to post/patch/put back some kind of update - then I need a ‘reverse’ transformer to get back to an object that my api wants to see.

Generically, I suppose my question could be boiled down to “how do I locally handle an api response object so that I can maintain its ‘purity’?”
Or something along those lines. I’m obviously fumbling for the correct terms and that is why i’m struggling to even google for info on this topic. For that I apologize and any help would be appreciated.

Also, I realize there is nothing Vue-specific about my question as this issue could apply to any data-driven ui framework.

Solution :

I think I get what you’re asking now. You just want to know if you need to modify the response before making it consumable by the UI. Let’s say you’re using axios. What I would do in vue.js is use the response.data object as the data to inject into the vue.js data property. For example, the response.data returns an array of objects. You would hardcode a data variable in vue.js like this:

data () {
return {
apiData: []
}
}

and with the API response, set the data array like this:

response => this.apiData = response.data;

Now apiData holds the unchanged representation from the db, including the ObjectId’s for each object. You can reference the array objects by the ObjectID within the UI, like this:

<div v-for=”item in apiData” :key=’item_id’ :item=”item”>
<p> {item.whateverProperty} </p>
</div>

[Vue.js] Vue.js method - Access to `this` within lodash _each loop Subscribe to RSS

My app has a list of collaborators, and a checkbox next to each one.

The user can check off multiple collaborators, then click a button to remove them, which triggers the following Vue.js method:

methods: {
remove: function () {
if (confirm(‘Are you sure you want to delete these collaborators?’)) {
axios.get(‘/collaborators/api/destroy’, {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {

// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, function (value, key) {

console.log(‘Remove collaborator: ‘ + value);

// Following line produces: TypeError: Cannot read property ‘collaborators’ of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)

});
});

}
},
// […etc…]

As you can see in the above code, when handling the ajax response, I attempt to loop through each of the selectedCollaborators using a lodash’s _each, and for each one, remove that collaborator from the collaborators data property using splice.

The problem is this.collaborators is not accessible within the _.each function and the following error is produced:

TypeError: Cannot read property ‘collaborators’ of undefined

How can I fix this/is there a better way to handle this?

Solution :

Try replace function to arrow function with lexical context:

methods: {
remove: () => {
if (confirm(‘Are you sure you want to delete these collaborators?’)) {
axios.get(‘/collaborators/api/destroy’, {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {

// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, (value, key) => {

console.log(‘Remove collaborator: ‘ + value);

// Following line produces: TypeError: Cannot read property ‘collaborators’ of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)

});
});

}
},

Solution 2:

What you can do is save this in a variable.

methods: {
remove: function () {
if (confirm(‘Are you sure you want to delete these collaborators?’)) {
axios.get(‘/collaborators/api/destroy’, {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {
const t = this;
// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, function (value, key) {
console.log(‘Remove collaborator: ‘ + value);
t.collaborators.splice(t.collaborators.indexOf(value), 1)
});
});

}
},
// […etc…]

[Vue.js] Can't get clientHeight in Vue js using $el Subscribe to RSS

to get client height of my app using this code :

mounted() {
document.onreadystatechange = () => {
if (document.readyState == “complete”) {
console.log(“Page completed with image and files!”);
console.log(this);
console.log(this.$el.clientHeight);
}
};
}

In console.log(this) I can see my main element and clientHeight of that is 702, but console.log(this.$el.clientHeight) result is 0.

Also I’m using Framework7 to creating my application UI.

What can I do about this problem?
Any help will greatly appreciate.

Solution :

Set a ref=”potato” on the component template, if that is an valid option for you, and then console.log(this.$refs.potato.clientHeight); will give you the component height.

[Vue.js] Dynamically data doesn't update when changing v-model input value in Vuejs Subscribe to RSS

when building a weather app with this Weather API. when trying to add an <input> field value that when it changes the city name, then updates the other values forecast.

there is created the <input> field which updates the city value & it should update the weather forecast accordingly. I know the v-model is working, however it doesn’t change the data results. Only when I hard-code a different city in the Vue-instance the data updates the changes.

<template>
<div class=”home”>
<h1>{ msg }</h1>
<p>A weather app built Vuejs & Open Weather App. Made by Manuel Abascal</p>
<input type=”text” v-model.lazy=”currentWeather.name”>
<div class=”forecast”>
<div v-if=”this.currentWeather”>
<!– Forecast stat values –>
<h2>Right now:</h2>
<div><strong>City:</strong> { currentCity }</div>
<div><strong>Longitude: </strong> { currentWeather.coord.lon }</div>
<div><strong>Latitude: </strong> { currentWeather.coord.lat }</div>
<div><strong>Weather condition </strong> { currentWeather.weather[0].description }</div>
<div><strong>Temperature Mid: </strong> { currentWeather.main.temp } Farenheit</div>
<div><strong>Temperature Max: </strong> { currentWeather.main.temp_max} Farenheit</div>
<div><strong>Temperature Min: </strong> { currentWeather.main.temp_min} Farenheit</div>
<div><strong>Humidity: </strong> { currentWeather.main.humidity }%</div>
<div><strong>Wind: </strong> { currentWeather.wind.speed } mph</div>
</div>
</div>
</div>
</template>

<script>
// import Axios
import axios from “axios”

export default {
name: “Home”,
props: {
msg: String,
},
data(){
return {
// current weather
currentWeather: null,
// current city
currentCity: ‘Montreal’,
// current country
currentCountry: ‘ca’,
unit: ‘imperial’
}
this.$set(this.currentCity);
},
mounted(){
// Make axios request to open weather api
axios.get(‘https://api.openweathermap.org/data/2.5/weather?q='+this.currentCity+','+this.currentCountry+'&appid=fe435501a7f0d2f2172ccf5f139248f7&units='+this.unit+'')
.then((response) => {
// takes response object & stores it in currentWeather
this.currentWeather = response.data

})
.catch(function (error) {
// handle error
console.log(error);
})
}
};
</script>

<style scoped lang=”scss”>

</style>

when trying when I change to cities like Montreal, Toronto, Ottawa, Alberta, etc..it changes the forecast accordingly. I need help.

Solution :

You have no event handler for currentCity changes. So the code will work on initial load (i.e on mounted) and changes to currentCity will not change any weather data.

You need to add @change to the input and fetch new api data every time it changes.

below is the sample code

new Vue({
el: ‘#app’,
data() {
return {
// current weather
currentWeather: null,
// current city
currentCity: ‘Montreal’,
// current country
currentCountry: ‘ca’,
unit: ‘imperial’
}
this.$set(this.currentCity);
},
methods: {
getWeather() {
// Make axios request to open weather api
fetch(‘https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ‘,’ + this.currentCountry + ‘&appid=fe435501a7f0d2f2172ccf5f139248f7&units=’ + this.unit + ‘’)
.then(res => res.json()).then(data => {
// takes response object & stores it in currentWeather
this.currentWeather = data;

})
.catch(function(error) {
// handle error
console.log(error);
})
}
},
mounted() {
this.getWeather();
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id=”app”>
<div class=”home”>
<p>A weather app built Vuejs & Open Weather App. Made by Manuel Abascal</p>
Search: <input type=”text” v-model.lazy=”currentCity” @change=”getWeather”>
<div class=”forecast” v-if=”currentWeather && currentWeather.cod == 200”>
<!– Forecast stat values –>
<h2>Right now:</h2>
<div><strong>City:</strong> { currentWeather.name }</div>
<div><strong>Longitude: </strong> { currentWeather.coord.lon }</div>
<div><strong>Latitude: </strong> { currentWeather.coord.lat }</div>
<div><strong>Weather condition </strong> { currentWeather.weather[0].description }</div>
<div><strong>Temperature Mid: </strong> { currentWeather.main.temp } Farenheit</div>
<div><strong>Temperature Max: </strong> { currentWeather.main.temp_max} Farenheit</div>
<div><strong>Temperature Min: </strong> { currentWeather.main.temp_min} Farenheit</div>
<div><strong>Humidity: </strong> { currentWeather.main.humidity }%</div>
<div><strong>Wind: </strong> { currentWeather.wind.speed } mph</div>
</div>
<div v-else>
“{ currentCity }” is not found
</div>
</div>
</div>

Solution 2:

There are 2 main issues that prevent the code from working as you expect.

v-model

The v-model in the input should be the currentCity data value, instead of the value in the response from the API, currentWeather.name.

This way, when the input changes, the currentCity will be updated, and you can react to it’s change and request new data.

requesting data

Having the request for the weather done in the mounted hook is fine to get the data one time only, since this hook isn’t executed again during the life of the component, a change in the city won’t do anything.

solution

I would change the v-model to be currentCity, and add a watcher on currentCity so when it changes, it triggers a call to a function that gets the weather, also, making this watcher immediate, will guarantee it runs on component mount as well.

there is a jsfiddle here with the updated code.

Solution 3:

You have two issues:

First, the input is bound the currentWeather.name instead of the currentCity

Second, you have the axios request in the mounted lifecycle. Even if the currentCity model change you are not defining what
will happen when it changes. You need to add an api call when the currentCity change.

Change the model of the input to the currentCity <input type=”text” v-model=”currentCity”>
Move the axios request to it’s own method

getWeather() {
const url = ‘https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ‘,’ + this.currentCountry + ‘&appid=fe435501a7f0d2f2172ccf5f139248f7&units=’ + this.unit + ‘’;
axios.get(url)
.then((response) => {
this.currentWeather = response.data;
})
.catch(function(error) {
console.log(error);
})
}

Bind the input change to the getWeather method

You can add the getWeather event to the input method of the currentCity input.

<input type=”text” v-model=”currentCity” @input=”getWeather”>

or add a watcher for the currentWeather

watch: {
currentCity: function(newCity, oldCity) {
this.getWeather();
}
}

bonus

every time you write down or erase a letter of the input the method is going to fire. Add a debounce or timeout and it will fire after the milliseconds.

// import Axios
import axios from “axios”

export default {
name: “Home”,
props: {
msg: String,
},
data() {
return {
currentWeather: null,
currentCity: ‘Montreal’,
currentCountry: ‘ca’,
unit: ‘imperial’
};
},
watch: {
currentCity: function(newCity, oldCity) {
this.debounceGetWeather();
},
},
mounted() {
this.getWeather();
},
methods: {
debounceGetWeather() {
setTimeout(() => {
this.getWeather();
}, 300);
},
getWeather() {
axios.get(‘https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ‘,’ + this.currentCountry + ‘&appid=fe435501a7f0d2f2172ccf5f139248f7&units=’ + this.unit + ‘’)
.then((response) => {
this.currentWeather = response.data ‘
})
.catch(function(error) {
console.log(error);
})
},
},
};

[Vue.js] Which is the best way to filter in a select input? Subscribe to RSS

I get this response from the API:

[
{
“id”: 6,
“nombre”: “Pechuga de pollo”,
“categoria”: “Pollo”,
“existencia”: 100
},
{
“id”: 7,
“nombre”: “Pierna de pavo”,
“categoria”: “Pollo”,
“existencia”: 100
},
{
“id”: 8,
“nombre”: “Lonja de pescado”,
“categoria”: “Pescado”,
“existencia”: 200
},
{
“id”: 9,
“nombre”: “Coca Cola”,
“categoria”: “Bebida”,
“existencia”: 200
},
{
“id”: 10,
“nombre”: “Jugo de naranja”,
“categoria”: “Bebida”,
“existencia”: 200
}
]

So I need to filter these json by the value “categoria”, then I’ll fill three differents select input on my template.

I tried with the filter() method but I guess I’m doing wrong:

///This is the function that filter needs on the argument:

filtradoBebida(bebida){
bebida.categoria == “Bebida”
},

///This is the function where I apply the filter method:

filtrarProductos(){
this.bebidas = productosLista.filter(filtradoBebida)
}

to fill a select with the json where the value categoria == “Bebida”, other select input with the json where the value == “Pollo”.

“bebidas” is an array from my data
“”productosLista” is an array that receives the response from the API.

Do you know another way to fill a select in vuejs by filtering a value of the json?

Solution :

You don’t use filter correctly.

What i suggest is to use an ES6 arrow function :

///This is the function where I apply the filter method:

filtrarProductos () {
this.bebidas = productosLista.filter(x => x.categoria === “Bebida”)
}

Solution 2:

Use a computed property. Here’s the basic outline of a component that can filter its items:

<template>
<ul>
<li v-for=”item in filteredItems” :key=”item.id”>{ item.text }</li>
</ul>
</template>

<script>
export default {
data() {
return {
// Set this via an API call
// Here we assume an item has: id, text, category
items: [],
// Use this as the v-model for a select
// Here we assume ‘’ is “no selection”
category: ‘’,
};
},
computed: {
filteredItems() {
// Show all of the items if there is not category filter
if (this.category === ‘’) return this.items;
return this.items.filter(item => item.category === this.category);
},
},
};
</script>

Solution 3:

I’m little bit confused with the comma which comes after filtradoBebida.
Seems like it is a property in some object.
Thus this is needed to call it from inside this object.

Also to be a correct filter predicate it should return a Boolean value.
Yours returns undefined always.

So, try

filtradoBebida(bebida){
return bebida.categoria == “Bebida”
},

///This is the function where I apply the filter method:

filtrarProductos(){
this.bebidas = productosLista.filter(this.filtradoBebida)
}

Solution 4:

You can also use, array.reduce to create a categoryMap where each category key can hold a list of similar category products. Then use this filtered product list to populate the 3 select components like so:

const productosLista = [{
“id”: 6,
“nombre”: “Pechuga de pollo”,
“categoria”: “Pollo”,
“existencia”: 100
},
{
“id”: 7,
“nombre”: “Pierna de pavo”,
“categoria”: “Pollo”,
“existencia”: 100
},
{
“id”: 8,
“nombre”: “Lonja de pescado”,
“categoria”: “Pescado”,
“existencia”: 200
},
{
“id”: 9,
“nombre”: “Coca Cola”,
“categoria”: “Bebida”,
“existencia”: 200
},
{
“id”: 10,
“nombre”: “Jugo de naranja”,
“categoria”: “Bebida”,
“existencia”: 200
}
]

const categoryMap = productosLista.reduce((acc, dt) => {
acc[dt.categoria] = acc[dt.categoria] ? […acc[dt.categoria], dt] : [dt]
return acc;
}, {});

console.log(categoryMap);

for (category in categoryMap) {
let sel = document.createElement(‘select’);
let categories = categoryMap[category];
categories.forEach(category => {
let option = document.createElement(“option”);
option.setAttribute(“value”, category.nombre);
option.text = category.nombre;
sel.appendChild(option);
});
document.body.append(sel);
}

[Vue.js] VueJs bind boolean values to dropdown Subscribe to RSS

there is a dropdown with two options: “True” and “False”, when selected, the form to save the selected value as a boolean.

So if I check the form value when the user has selected “True”, the value to be true as a boolean.

<select v-model=”selected”>
<option :value=”null”>Pick a value</option>
<option v-for=”val in options”>{val}</option>
</select>

data() {
return {
selected: null,
options: [“true”, “false”]
}

Here is a fiddle of what when attempting:
https://jsfiddle.net/q0nk9h32/5/

How can I output the selected values in their boolean form?

Bonus question: Instead of having the options variable, is it valid syntax / good practice, to do:

v-for=”val in [“true”, “false”]“ ?

It seems overkill to have a variable for this (but it fails in fiddle when I try using an array directly). Thanks!

Solution :

You can bind a value to each <option> using :value.

https://vuejs.org/v2/guide/forms.html#Select-Options

new Vue({
el: ‘#app’,
data() {
return {
selected: null
}
}
});
<script src=”https://unpkg.com/vue"></script>

<div id=”app”>
<select v-model=”selected”>
<option :value=”null”>Pick a value</option>
<option v-for=”val in [true, false]“ :value=”val”>{val}!!!</option>
</select>
<p>
Selected is the { typeof selected }: { selected }
</p>
</div>

You can write the array for a v-for inline if you want. In the original example it wouldn’t have worked because you included double quotes around the strings but were already using double quotes around the attribute.

You’ve got lots of options for rendering the text as True and False for these values…

If you just have two values, true and false, I’d be inclined to drop the v-for altogether and just write them separately.

<option :value=”null”>Pick a value</option>
<option :value=”true”>True</option>
<option :value=”false”>False</option>

Alternative ways of formatting the text would be to use a filter or method. So that’s:

<option v-for=”val in [true, false]“ :value=”val”>{ val | filter }</option>

or

<option v-for=”val in [true, false]“ :value=”val”>{ method(val) }</option>

For a filter you’d define it in the component’s filters section, for a method it’d be in the methods. Either way the function just needs to convert the boolean value to a string and then uppercase the first letter.

// Obviously you wouldn’t call it ‘method’…
method (value) {
const str = String(value);
return str.charAt(0).toUpperCase() + str.slice(1);
}

That said, given there are only two possible options, there are all sorts of other ways to do it. e.g.:

<option v-for=”val in [true, false]“ :value=”val”>{ val ? ‘True’ : ‘False’ }</option>

Solution 2:

One option would be to create a computed property that just returns this.selected === ‘true’.

[Vue.js] Highlighting duplicate words in an HTML page Subscribe to RSS

there is a table that contains v-html results (thus the text inside the table would not be there until the page is rendered). I would like to compare two rows and if they have duplicate words then they should be highlighted.

Here is an example project of what I wanted, but way beyond the scope of what I need. My question seems most like this one in the stacks but it requires that the words be defined, the page to find them itself.

For example, this would be the expected output:

<table>
<tr>
<td v-html=”link.orderdesciption”>
order:<br />
<mark> TV </mark><br /> <!–note that the contents of the td would not appear in markup due to being v-html–>
PS3 <br />
Laptop
</td>
<td>
qty:<br />
1<br />
2<br />
1<br />
</td>
</tr>
<tr>
<td>
-—————
</td>
<td>
-—————
</td>
</tr>
<tr>
<td v-html=”link.orderrecieved”>
recieved:<br /> <!–same note as above, v-html only shows–>
<mark> TV </mark><br />
Desktop<br />
</td>
</tr>
</table>

I’ve been working on this but there is really no idea where to go from here:

var text = $(‘td’).text(),
words = text.split(‘ ‘),
sortedWords = words.slice(0).sort(),
duplicateWords = [];

for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);

Thanks for any advice,

Solution :

Use reduce to get the duplicate words, then you can iterate over tds to check in the text in it is present
within the duplicate words Array. If yes, then wrap the the text in mark tag.

const tds = document.querySelectorAll(‘td’);

const groupByOccurence = […tds].reduce((accu, td) => {
const textArr = td.innerHTML.split(‘<br>’).map((word) => word.trim()).filter((word) => word.length > 0 && word.match(/[a-zA-Z]+/g));
textArr.forEach((text) => {
accu[text] = (accu[text] || 0) + 1;
});
return accu;
}, {});

const duplicateWords = Object.entries(groupByOccurence).filter(([_, val]) => val > 1).map(([key, _]) => key);

tds.forEach((td) => {
const textArr = td.innerHTML.split(‘<br>’).map((word) => word.trim());
let str = “”;
textArr.forEach((text) => {
if (duplicateWords.includes(text)) {
str += ‘<mark>’ + text + ‘</mark><br>’;
} else {
str += text + ‘<br>’;
}
td.innerHTML = str;
})
});

const trs = document.querySelectorAll(‘tr’);

trs.forEach((tr, i) => {
const specialChartds = […tr.querySelectorAll(‘td’)].filter((td) => !td.textContent.match(/[a-zA-Z]+/g));
if (!specialChartds) {
tr.append(tds[i]);
}
});
<table>
<tr>
<td>
order:<br /> TV
<br /> PS3 <br /> Laptop
</td>
<td>
qty:<br /> 1
<br /> 2
<br /> 1
<br />
</td>
</tr>
<tr>
<td>
-—————
</td>
<td>
-—————
</td>
</tr>
<tr>
<td>
recieved:<br /> TV <br /> Desktop
<br />
</td>
</tr>
</table>

Solution 2:

To achieve expected result, use below option

Getting all words from table by looping $(‘table’) with each
Creating array with all duplicate words from step1 using filter method
Looping all tds with each and adding mark tag for duplicate words

var text = $(‘table’);
var arr = [];

//Step 1: Getting All words from table
var words = text.each(function(){
let val = $(this).text().replace(/\n|\r/g,’ ‘).split(‘ ‘).filter(Boolean);
arr.push(…val)
})

//Step 2: Finding duplicate words
let duplicate = arr.filter(function(value,index,self){ return (self.indexOf(value) !== index && isNaN(parseInt(value)) && value.match(/[A-Za-z]/) !== null)})

//Step 3: Marking duplicate words in each row
$(‘td’).each(function(){
let val = $(this).text();
let openMark = ‘<mark>’
let closeMark = ‘</mark>’
duplicate.forEach(v => {
if(val.indexOf(v) !== -1){
var html = $(this).html().replace(v, openMark + v + closeMark)
$(this).html(html)
}
})
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
order:<br />
TV<br />
PS3 <br />
Laptop
</td>
<td>
qty:<br />
1<br />
2<br />
1<br />
</td>
</tr>
<tr>
<td>
-—————
</td>
<td>
-—————
</td>
</tr>
<tr>
<td>
recieved:<br />
TV<br />
Desktop<br />
</td>
</tr>
</table>

codepen - https://codepen.io/nagasai/pen/YoPPMv?editors=1010

[Vue.js] Format option in vue-datetime wrong format Subscribe to RSS

I’m using vue-datetime plugin, it appears as if the format option doesn’t work as expected, see below:

<datetime type=”date” v-model=”formData.testDate” input-class=”form-control” format=”DateTime.DATE_SHORT”></datetime>

It should output as: DD/MM/YYYY but instead outputs as a random string of characters.

Solution :

You are trying to apply a format to a string. The format should bind to a variable, the variable needs to reference the wanted format option of the DateTime module of luxon.

<template>
<div id=”app”>
<datetime type=”date” v-model=”formData.testDate” input-class=”form-control” :format=”format” />
</div>
</template>

<script>
import { DateTime } from ‘luxon’;

export default {
name: ‘app’,
components: {
},
data: () => ({
formData: {
testDate: ‘’,
},
format: DateTime.DATE_SHORT,
}),
}
</script>

[Vue.js] How to create v-autocomplete which first shows items startsWith and then shows items indexOf Subscribe to RSS

I would like to create a vuetify autocomplete with a custom filter that first shows the hits that start with the searchtext and then show the hits that not start with the searchtext, but have the searchtext somewhere in the middle.

I now have a custom filter like this, but this filter is not prioritizing words that start with the searchtext:

customFilter(item, queryText) {
const textOne = item.description.toLowerCase();
const textTwo = item.code.toLowerCase();
const searchText = queryText.toLowerCase();

return (
textOne.indexOf(searchText) > -1 || textTwo.indexOf(searchText) > -1
);
}
},

Solution :

Codepen (Type ‘ma’ for example)

I believe you need to sort it manually, filter returns only true/false whether item is a match.

// https://stackoverflow.com/a/36114029/1981247
var _sortByTerm = function (data, term) {
return data.sort(function (a, b) {
// cast to lowercase
return a.toLowerCase().indexOf(term) < b.toLowerCase().indexOf(term) ? -1 : 1;
});
};

Then pass sorted array to items prop

<v-autocomplete :items=”computedItems”

computed: {
computedItems() {
return _sortByTerm(this.states, this.search.toLowerCase())
},
},

Note this is just to get you started, and you might need to change code a bit according to the data (and filters) you are using, e.g. _sortByTerm works only on array of strings, but in the link there is a solution for sorting arrays of objects also.

[Vue.js] Displaying data inside multiple arrays Subscribe to RSS

So there is this data: https://i.stack.imgur.com/Sga6H.png and when displaying it like this;

<tr v-for=”cv_identifying_info in cv_identifying_infos” :key=”cv_identifying_info”>
<td>{ cv_identifying_info[‘person-info’] }</td>

Now to access the further data inside. I tried like

<td>{ cv_identifying_info[‘person-info’][‘full-name’]}</td>

and other ways but it gives me the error

Cannot read property ‘full-name’ of undefined

but how can it be undefined if could access the data using only

cv_identifying_info[‘person-info’]

?And also

Duplicate keys detected: ‘[object Object]‘. This may cause an update
error.

It’s not like there is an id or a name to do :key=”cv_identifying_info.id”

Kinda confused here, any suggestion?

Solution :

{ cv_identifying_info[‘person-info’] }

Is similar to echo cv_identifying_info[‘person-info’].

That means that you have not an array or an object there, but a string, so you can not access anything further than that.

That’s why you get this message

Cannot read property ‘full-name’ of undefined

In case $cv_identifying_info[‘person-info’][‘full-name’] existed you would get an error for

array to string conversion

using the above code but based on what you say you don’t.

That means that person-info field is not the key for a nested array but for a string value. try to print_r the root array $cv_identifying_info to see the structure of it.