link1781 link1782 link1783 link1784 link1785 link1786 link1787 link1788 link1789 link1790 link1791 link1792 link1793 link1794 link1795 link1796 link1797 link1798 link1799 link1800 link1801 link1802 link1803 link1804 link1805 link1806 link1807 link1808 link1809 link1810 link1811 link1812 link1813 link1814 link1815 link1816 link1817 link1818 link1819 link1820 link1821 link1822 link1823 link1824 link1825 link1826 link1827 link1828 link1829 link1830 link1831 link1832 link1833 link1834 link1835 link1836 link1837 link1838 link1839 link1840 link1841 link1842 link1843 link1844 link1845 link1846 link1847 link1848 link1849 link1850 link1851 link1852 link1853 link1854 link1855 link1856 link1857 link1858 link1859 link1860 link1861 link1862 link1863 link1864 link1865 link1866 link1867 link1868 link1869 link1870 link1871 link1872 link1873 link1874 link1875 link1876 link1877 link1878 link1879 link1880 link1881 link1882 link1883 link1884 link1885 link1886 link1887 link1888 link1889 link1890 link1891 link1892 link1893 link1894 link1895 link1896 link1897 link1898 link1899 link1900 link1901 link1902 link1903 link1904 link1905 link1906 link1907 link1908 link1909 link1910 link1911 link1912 link1913 link1914 link1915 link1916 link1917

[Vue.js] How do I replace NaN with 0 when doing division in javascript?

when trying to do simple division using .map() on an array of objects. However when zero divided by zero returns NaN. How to I check for this calculation and return the number 0 instead of NaN?

mounted() {
console.log(this.dataOverview);
let newData = this.dataOverview.map((data) => {
return {
conversationSource: data.conversationSource,
Id: data.Id,
answerableConversations: data.conversationCount,
interactiveConversations: data.interactive,
leads: data.sent,
interactiveLeadConversations: ((data.sent / data.interactive) * 100).toFixed(0)
}
})
this.convertedData = newData;
console.log(this.dataOverview);
}

Using this, interactiveLeadConversations returns NaN when both data.sent and data.interactive are zero.

Solution :

You don’t need to explicitly check. This should be the line 10:

interactiveLeadConversations: (((data.sent / data.interactive) || 0) * 100).toFixed(0)

What I’m doing here is to replace the expression

(data.sent / data.interactive)

with

( (data.sent / data.interactive) || 0 )

NaN evaluates to false, so if the expression (data.sent / data.interactive) equals NaN, you are offering 0 as alternative.

[Vue.js] How do I upload both images and form content in a vue

Upload images and form content? How to upload? The idea is to upload it to the client and then upload it to the server along with the form content, right?

to upload the form content and the image to the server when I click submit, instead of uploading the image separately when I upload the image.
But I don’t know how to upload at the same time. Can you help me?

<template>
<form>
<input type=”text” v-model=”test”>
<img :src=”previewImage” class=”uploading-image” />
<input type=”file” accept=”image/jpeg” @change=uploadImage>
<input type=”submit”></input>
</form>
</template>

export default {
data(){
return{
previewImage:null,
test: ‘’
}
},
methods:{
uploadImage(e){
const image = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = e =>{
this.previewImage = e.target.result;
console.log(this.previewImage);
};

const URL = ‘http://xxxx';

let data = new FormData();
data.append(‘name’, ‘my-picture’);
data.append(‘file’, event.target.files[0]);

let config = {
header : {
‘Content-Type’ : ‘image/png’
}
}
axios.put(URL, data,config).then(response => {
console.log(‘image upload response > ‘, response)
})
}

}

Solution :

You need to add this to the form

<form @submit.prevent=”uploadImage”>
<input type=”text” v-model=”test”>
<img :src=”previewImage” class=”uploading-image” />
<input type=”file” accept=”image/jpeg” >
<input type=”submit”></input>
</form>

[Vue.js] It's there any way to get v-model's variable name in the parent component from a child component

For case below, when I customize a vue.js component of radio, I can use model option to get the v-model value which should be a string ‘1’.How can I get its variable name ‘radio1’ in the child? It’s there any way?

the child component

<template>
<input type=”radio” v-model=”prop” :value=”value”>
</template>
<script>
export default {
model: {
prop: “prop”
},
props: {
prop: {
default: ‘’
},
value: {
default: ‘’
}
}
}
</script>

the parent use this component

<template>
<div>
<radio-component v-model=”radio1” value=”1”></radio-component>
<radio-component v-model=”radio1” value=”2”></radio-component>
</div>
</template>
<script>
import radioComponent from ‘./radio’
export default {
components: {
radioComponent
},
data () {
return {
radio1: ‘1’
}
}
}
</script>

Solution :

You can emit an event with any name you want, so in the child you can write:

<input type=”radio” @input=”$emit(‘prop’, prop)” v-model=”prop” :value=”value”>

Then in the parent you can do:

<radio-component v-model=”radio1” @prop=”doSomething” value=”1” name=”nameValue”></radio-component>
.
.
.
data(){
return {
nameValue: null
}
methods: {
doSomthing(prop){
this.nameValue = prop
}
}

[Vue.js] How to set focus on input field in Vuejs when field loads conditionally with v-if

My form has a first name and last name that initially appear as one compact string, but split into two input fields when the user clicks on the string. I need these two input fields to disappear and revert back to the compact string format when the user clicks elsewhere on the page (anywhere other than inside those two input fields). In order to achieve this, I use a v-on directive with the blur attribute. This works well, but only if the user first clicks into one of the input fields to trigger focus. This is because blur only triggers on an input field that is already in focus. Is there either a way for me to automatically put the first input field in focus when the input element conditionally renders? Is there a better approach?

Cheers.

Here is my HTML:

<a v-if=”!eitherNameSelected” @click=”firstNameSelected”>
{person.firstname} {person.lastname}</a>
<div class=”row” v-else-if=”eitherNameSelected” v-enter=”focusOnFirstChild($event)”>
<div class=”col-md-3”>
<input
@focus=”firstnameselected=true”
@blur=”firstnameselected=false”
type=”text”
class=”form-control”
name=”example-text-input-invalid is-invalid”
id=”firstname”
placeholder=”First Name”
v-model=”person.firstname”
\>

<div class=”invalid-feedback”>
Invalid feedback
</div>
</div>
<div class=”col-md-3”>
<input
@focus=”lastnameselected=true”
@blur=”lastnameselected=false”
type=”text”
class=”form-control”
name=”example-text-input-invalid is-invalid”
placeholder=”Last Name”
v-model=”person.lastname”
\>
<div class=”invalid-feedback”>
Invalid feedback
</div>

And in my Javascript …

data() {
return {
listid: 0,
listname: “”,
personid: 0,
person: {},
nameselected: false,
activetab1: “main”,
activetab2: “notes”,
firstnameselected: false,
lastnameselected: false,

….

methods: {
firstNameSelected() {
var elem = vm.$el.getElementById(‘firstname’);
elem.focus();
this.firstnameselected=”true”;
}
},
computed: {
eitherNameSelected() {
return (this.firstnameselected || this.lastnameselected);
}
},

Solution :

put an @click=someFunction (or computed) on the root element (i.e. the whole body of HTML) and then have that change the text.

Solution 2:

It may not be the best solution but you could use a @click($event) in order to know where you clicked to hide or not the inputs.

This post about checking event targets can be a good start I guess.

I also coded a minimal example to help you get through the issue. I hope it will help you.

new Vue({
el: “#app”,
data: {
person: {
firstname: ‘PersonFirstname’,
lastname: ‘PersonLastname’
},
showCompactString: true
},
methods: {
onCompactStringClicked() {
this.showCompactString = false
},

// Hide the inputs if a click is triggered outside of them
onAppClicked(event) {
// Do nothing if compact string is being shown
if (this.showCompactString)
return

const fistnameInputClickedOn = event.target.matches(‘#firstname’)
const lastnameInputClickedOn = event.target.matches(‘#lastname’)
const anyInputClickedOn = fistnameInputClickedOn || lastnameInputClickedOn

if (!anyInputClickedOn)
this.showCompactString = true
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app” @click=”onAppClicked($event)”>
<a v-if=”showCompactString” @click.stop=”onCompactStringClicked”>{person.firstname} {person.lastname}</a>
<div class=”row” v-else>
<div>
<input type=”text” id=”firstname” placeholder=”First Name” v-model=”person.firstname”>
</div>
<div>
<input type=”text” id=”lastname” placeholder=”Last Name” v-model=”person.lastname”>
</div>
</div>
</div>

Don’t hesitate to leave a comment if you have trouble. I’ll answer you back as fast as I can.

[Vue.js] Deleting an object with Axios, Vue, Laravel

i’m trying to delete an object both from my view & my mySQL DB, however i’m encountering this error:
DELETE http://localhost:8000/api/machines/\[object%20MouseEvent\] 404 (Not Found)

If i remove the axios call, this method deletes the object from the view (of course when i reload the page it’s back because i don’t persist it to the DB.

Here’s how the method looks:

removeElement(index) {
axios
.delete(“machines/“ + index)
.then(res => {
confirm(“Are you sure you want to delete this item?”) &&
this.machines.splice(index, 1);
})
.catch(err => {
console.log(err);
});
},

Here’s how the route looks:

Route::delete(‘machines/{id}’, [
‘as’ => ‘machines/{id}’,
‘uses’ => ‘MachineController@destroy’
]);

And here’s how the controller looks:

public function destroy(Request $request, $id)
{
$machines = Machine::findOrFail($request->id)->delete();
}

Can someone help me out or atleast point me in the right direction? Thanks in advance!

Solution :

http://localhost:8000/api/machines/\[object%20MouseEvent\]

this isnt correct URL. Looks like you need to get machine ID instead and use it request.

Try to use removeElement(machine.id) instead of that you are doing now.

If that’s not enough, please share vue/js code with removeElement call in it

[Vue.js] How to Get the Values of $emit Payload in Vuejs

I’m new to vuejs and had to use date range picker. I’m using vue-rangedate-picker and after selecting a date range, $emit type event is fired and I found the required values in the payload of the event as shown below (event info taken from vue.js debugger):

name: “selected”
type: “$emit”
source: “<vue-rangedate-picker>”
payload: Array[1]
0: Object
end: “Fri May 31 2019 05:30:00 GMT+0530 (India Standard Time)”
start: “Wed May 01 2019 05:30:00 GMT+0530 (India Standard Time)”

I need to get the values in payload so I can assign to variables and use them later. I tried to find the solution for hours and had no luck.
Here is the element

<vue-rangedate-picker
righttoleft=”true”
i18n=”EN”
format=”YYYY-MM-DD HH:mm:ss”
@selected=”testDatePicker()”
\></vue-rangedate-picker>

And the script

testDatePicker() {
console.log(/*what should I write here to get the payload?*/);
}

How do I get the payload values so I can assign them to variables? Please help me.

Solution :

the function testDatePicker will receive the range in the following form:

testDatePicker({start, end}) {
console.log(start, end);
}

or if you prefer:

testDatePicker(range) {
console.log(range.start, range.end);
}

Also, you should not use parenthesis in the call:

<vue-rangedate-picker
righttoleft=”true”
i18n=”EN”
format=”YYYY-MM-DD HH:mm:ss”
@selected=”testDatePicker”
\></vue-rangedate-picker>

Like that, you pass a “reference” to the method, and the component will call it with needed parameters.

[Vue.js] vue router stop scrolling

I don’t want to scroll to the the anchor when doing this.$router.push(‘#something’); if when not mistaken we will use scrollBehavior but I don’t know how
there is been doing

this.$router.options.scrollBehavior = ()=>{
return false
}

but it doesn’t work

Solution :

Can you try this code, I guess it will prevent scroll to the bottom(y-axis) if url has a hash

export default new Router({
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return { y: 0 }
}
}


})

[Vue.js] Default-expand-all doesn't work for q-tree? Vue.Js

there is to code a web application and the most important element is the q-tree. I’m already able to load and show data (passing an array called list), but that all nodes are expanded.

The vue.js examples of the official documentation show that you’re be able to do this with the ‘default-expand-all’ attribute but this isn’t working for me.

It only shows me the root node with an arrow, where there is to expand the children nodes manually.

<q-tree
:nodes=”list”
:selected.sync=”selected”
@update:selected=”onSelectionChangedNode”
node-key=”NodeNr”
label-key=”NodeTxt”
default-expand-all
\></q-tree>

Solution :

The default-expand-all is only applied on the first rendering of that Component.
So if the Component renders when the nodes aren’t assigned they wont expand if assigned afterwards.

https://v1.quasar-framework.org/vue-components/tree

You have to work with scoped slots and an expanded attribute if you dont have the nodes on first rendering.

Solution 2:

Solved my problem as following:

there is added a ref attribute to the QTree DOM Element which makes it possible to access predefined methods of QTree API.

<q-tree
:nodes=”list”
:selected.sync=”selected”
@update:selected=”onSelectionChangedNode”
node-key=”NodeNr”
label-key=”NodeTxt”
**ref=”nodes”**
\>

The method there is been using is expandAll().

updated() {
this.$refs.nodes.expandAll();
}

The most important thing for me was, I had to find out which lifecycle hook was the right one for me. The update() hook was the one I was looking for.

The reason:

Called after a data change causes the virtual DOM to be re-rendered and
patched.

The components DOM will have been updated when this hook is called, so you
can perform DOM-dependent operations here.

[Vue.js] Printing unesacped HTML to elements.io table with vue.js

I would like to print some HTML data to elements table with vue.js.

new Vue({
el: “#app”,
data: {
todos: [
{ text: “<p>Learn JavaScript</p>”, done: false },
{ text: “<p>Learn Vue</p>”, done: false },
{ text: “<p>Play around in JSFiddle</p>”, done: true },
{ text: “<p>Build something awesome</p>”, done: true }
]
},
})

and my template is

<div id=”app”>
<el-table :data=”this.todos”>
<el-table-column prop=”text”></el-table-column>
</el-table>
</div>

But when I run, it prints <p>Learn JavaScript</p> unescaped. I would like to print it as rendered as HTML.

Solution :

I found it by scoped template… Works like this…

<div id=”app”>
<el-table :data=”this.todos”>
<el-table-column prop=”text”>
<template scope=”scope”>
<span v-html=”scope.row.text”/>
</template>
</el-table-column>
</el-table>
</div>

[Vue.js] How do I sort a table alphabetically and numerically in vue.js?

I’m currently working on sorting functionality on a table built with vue.js. there is ascending sorting currently working with numbers. However when unable to get the descending and alphabetical functionality to work properly.

Here is my html where when calling the sort functionality. Currently there is this as a method().

<tr class=”dash-table-mainHead”>
<th
v-for=”(column, key) in columns”
:key=”key”
@click=”sortTable(column)”
\>{ column.label }</th>
</tr>

Here is the javascript where there is my array of columns with appropriate fields.

data() {
return {
columns: [
{ label: this.$t(‘reporting.source’), field: ‘source’ },
{ label: this.$t(‘reporting.accountsWithActivity’), field: ‘accountsWithActivity’, align: ‘center’, type: ‘icon’ },
{ label: this.$t(‘reporting.answerableConversations’), field: ‘answerableConversations’, type: ‘boolean’, align: ‘center’ },
{ label: this.$t(‘reporting.interactiveConversations’), field: ‘interactiveConversations’, type: ‘boolean’, align: ‘center’ },
{ label: this.$t(‘reporting.leads’), field: ‘leads’, align: ‘center’ },
{ label: this.$t(‘reporting.interactiveLeadConversations’), field: ‘leads’, type: ‘date’ },
{ field: ‘blank’ },
],

convertedData: [],
// currentSort: ‘name’,
currentSortDir: ‘asc’,

}
},

And finally my method where when doing the sorting. This currently works for ascending only and doesn’t appear to be sorting alphabetically.

methods: { sortTable(column) {
console.log(column.field)
let sortedData = [];

sortedData = this.convertedData.sort((a, b) => {
if (a[column.field] < b[column.field]) { return -1; }
if (a[column.field] > b[column.field]) { return 1; }
return 0;
})
}
}

Solution :

Use a computed property sortedData for the items and put that in the template instead of convertedData
If comparing strings, use String.localCompare.
Add a sortField data property.
Simply set the sortField to null or the clicked field value to make the magic happen.

@click=”sortField=column.field”

let component = {
data() {
return {
// convertedData: …
sortField: null,
currentSortDir = ‘asc’
}
},
computed: {
sortedData() {
if (this.sortField === null) {
return this.convertedData;
}
return this.convertedData.sort((a, b) => {
let res;
if (typeof a[this.sortField] === ‘string’) {
res = a[this.sortField].localeCompare(b[this.sortField])
} else {
res = a[this.sortField] > b[this.sortField] ? 1 :
a[this.sortField] < b[this.sortField] ? -1 : 0
}
if (this.currentSortDir !== ‘asc’) {
ret = ret * -1;
}
return ret
})
}
}
}

If you have null/undefined values you will have to do some more work checking the types.

It is now very easy to sort multiple fields. And the sort direction can be reactive as well by just updating the sort direction data property.