link274 link275 link276 link277 link278 link279 link280 link281 link282 link283 link284 link285 link286 link287 link288 link289 link290 link291 link292 link293 link294 link295 link296 link297 link298 link299 link300 link301 link302 link303 link304 link305 link306 link307 link308 link309 link310 link311 link312 link313 link314 link315 link316 link317 link318 link319 link320 link321 link322 link323 link324 link325 link326 link327 link328 link329 link330 link331 link332 link333 link334 link335 link336 link337 link338 link339 link340 link341 link342 link343 link344 link345 link346 link347 link348 link349 link350 link351 link352 link353 link354 link355 link356 link357 link358 link359 link360 link361 link362 link363 link364 link365 link366 link367 link368 link369 link370 link371 link372 link373 link374 link375 link376 link377 link378 link379 link380 link381 link382 link383 link384 link385 link386 link387 link388 link389 link390 link391 link392 link393 link394 link395 link396 link397 link398 link399 link400 link401 link402 link403 link404 link405 link406 link407 link408 link409 link410

[Vue.js] Cannot Load CSS file with Vue packaged library (npm)

when using vue-cli to build a librabry (npm package) to work for both SSR and client side. All seems to be working a part from that the CSS loads only if the component is present in the page that is being refreshing. However, if access any other pages that there is not the component, and then navigate (vue-route) to the page that the component is present, the CSS is not being loaded.

Currently, I need to import the lib as well as the CSS which I think is not ideal like so

import vue.js from ‘vue’;
import myLib from ‘myLib’;
import ‘myLib/dist/myLib-ssr.css’;

Vue.use(myLib);

Any thoughts to fix it?

Solution :

According to this thread

you Just need to include it in the /main.js file like this…

<script>
require(‘@/assets/css/main.css’)
</script>

if it doesn’t work then npm install style-loader css-loader and then in the webpack.config.js add this

module: {
rules: [
{
test: /\.css$/,
use: [ ‘style-loader’, ‘css-loader’ ] // <= Order is very important
}
]
}

and then require again in the /main.js file

If you are using an outside library like materialize for example then

import vue.js from ‘vue’
import App from ‘./App’
import router from ‘./router’
//import the library and its css files
import materialize from ‘materialize-css’
import ‘materialize-css/dist/css/materialize.min.css’
//then use it as a global plugin
Vue.use(materialize)

new Vue({
el: ‘#app’,
//load it in the main.js file
router, materialize,
components: { App },
template: ‘’
})

[Vue.js] How to list options in an alphabetical order vuejs

How to list the options in an alphabetical order.when running a quiz app from the code here.I need to list the responses in a alphabetical order. How do I do that?

Below is the list of questions that is sent to the template

Reponse

var quiz = {

title: ‘My quiz’,

questions: [

{

text: “Question 1”,

responses: [

{text: ‘Wrong, too bad.’},

{text: ‘Right!’, correct: true},

]

}, {

text: “Question 2”,

responses: [

{text: ‘Right answer’, correct: true},

{text: ‘Wrong answer’},

]

}

]

};

when trying to use filters

Vue.filter(‘myMapping’,function(index){
mapping = [“A”, “B”, “C” , “D”, “E”];
return mapping[index];
});

<div class=”ques_block” v-for=”(question, index) in quiz.questions”>

<div v-show=”index === questionIndex”>
<h3>{index + 1}) {question.text}</h3>
<div class=”option_div” v-for=”(response,resp) in question.responses”>
<input type=”radio” v-bind:name=”index” v-bind:value=”response.correct” v-model=”userResponses[index]“/>
<label> {resp| myMapping}) {response.text} </label>
</div>
</div>
</div>

Jsfiddle Link

Solution :

This is more of a javascript problem than a vuejs problem. You would want to sort the array before displaying it.

after declaring the array you can run this sort snippet.

quiz.questions.sort((a, b) => a.text.localeCompare(b.text));
quiz.questions.forEach(({ responses }) => responses.sort((a, b) => a.text.localeCompare(b.text)));

What this does is to sort the outer “object” while using the key (text) in ascending order, once the outer object has been sorted, you loop through the responses array inside the object to sort each object using the key(text) in ascending order.

[Vue.js] How can I use template tag inside slot in VueJS?

there is a template that includes some HTML along with some script tags. to use it inside my vue.js component as a template that later I will place into the DOM and I would like it to be placed as is, so my script tags are also executed.

I would like to keep the template inside the component tag and use a slot.

e.g.

<amazing-component>
<template>
<p>This is the content</p>
<script>
console.log(“to be executed as long as someone puts me in the DOM!”);
</script>
</template>
</amazing-component>

<script type=”text/x-template” id=”component-template”>
<slot></slot>
</script>

But the problem is that vue.js removes the template and the script tags and then replaces the slot tag.

What I’ve desperately tried so far and didn’t work:

Put the template inside another template - the template just disappears.
Wrap the slot with a template - the template just disappears.
Use a <script type=”text/x-template” > - that was an epic failure.
Get the slot from $slots - It is a VNode that doesn’t have template/script tags.

The biggest problem is that the front-end doesn’t have a clue of what the html inside the template tag looks like. It is just some html that is rendered on the server, some immutable legacy code that has to be inserted as-is in the page in order to work.

Of course I can put the template tag outside of the component and fetch it another way, but I would like to have it inside the component to keep it a bit more tidy and elegant.

Solution :

That’s not how vue.js works. <script> tags do not belong in the <template> and are omitted for a reason. If you want something to be executed on page load, use a coresponding hook

To execute server generated JS code use eval()

Parent.vue

<template>
<child script=”console.log(‘something’)”></child>
</template>

Child.vue

<template>

</template>

<script>
props: [‘script’],
created() {
eval(this.script)
}
</script>

Solution 2:

While vue.js consumes template tags in its own compiling, you can still force it to emit HTML template tags by using <component is=”template”>

var app = new Vue({
el: ‘#app’,
template: `
<div>
<h1>No template:</h1>
<template>
test
</template>
<p>More code (check the page source)</p>
<h1>Yes template: </h1>
<component is=”template”>
test
</component>
<p>More code(check the page source)</p>
<h1>Yes script: </h1>
<component is=”script”>
console.log(‘Scrpt test’);
</component>
<p>More code(check the console)</p>
</div>
`,
data: {}
})
<!– development version, includes helpful console warnings –>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id=”app”></div>

[Vue.js] What is the proper way to add same component everytime a button is clicked?

when creating a form which needs to have a button and when clicked a new component which is only an input field would be added.

For example there is only one field to put in my address, but my adress is very long so I need 2 additional input fields. I click a button twice and two more components with the input appear.

What is a proper way to achieve this functionality?

Solution :

Here is a simple solution to the question.
https://jsfiddle.net/RiddhiParekh/usd57zkb/6/

Template =>

<div id=”vue-instance”>
<button @click=”addInput”>Click to add input</button>
<br>
Address:
<div v-for=”i in count”>
<input type=”text”>
</div>
</div>

Script =>

var vm = new Vue({
el: ‘#vue-instance’,
data: {
count:1
},
methods:{
addInput(){
this.count = this.count+1
}
}
});

[Vue.js] Vue - Pushing array into nested array from callback

I’m encoding images into base64 format in a component then trying to push the objects into an array.

Basically collection Item > Collection Item Images

<base64 :index=”index” :multiple=”true” :done=”getFiles”></base64>

colItems: [
{
id: ‘1’,
title: ‘Title 1’,
subTitle: ‘Subtitle 1’,
colItemImgs: [],
},
],

methods: {
// Add images to ColItem
getFiles(files) {
console.log(files)
this.colItems.colItemImgs.push(…files)
},
}

I’m trying to specifically add them into the right object using the index. But haven’t figured out how to pass the index back through the callback.

Thanks for the time

Base64 Component

<template>
<div>
<v-btn raised @click=”onPickItemFile(index)”>base64</v-btn>
<input type=”file” @change=”onChange” :multiple=”multiple”
style=”display: none” ref=”foobar_y” />
</div>
</template>

<script>
export default {
props: {
multiple: {
default: false,
type: Boolean,
},
done: {
type: Function,
default: () => {}
},
index: ‘’,
},
methods: {
onChange(e){
// get the files
let files = e.target.files;
// Process each file
var allFiles = []
for (var i = 0; i < files.length; i++) {
let file = files[i]
// Make new FileReader
let reader = new FileReader()
// Convert the file to base64 text
reader.readAsDataURL(file)
// on reader load somthing…
reader.onload = () => {
// Make a fileInfo Object
let fileInfo = {
name: file.name,
type: file.type,
size: Math.round(file.size / 1000)+’ kB’,
base64: reader.result,
file: file
}
let index = this.index
// Push it to the state
allFiles.push(fileInfo)
// If all files have been proceed
if(allFiles.length == files.length){
// Apply Callback function
if(this.multiple) this.done(allFiles)
else this.done(allFiles[0])
}
} // reader.onload
} // for
}, // onChange()
onPickItemFile (index) {
this.$refs.foobar_y.click()
},
}
};
</script>

Solution :

colItems is an Array, like a = [1,2,3,4] if you want to access specific element inside array you need to provide index of that element like a[0] // result-> 1. so colItemImgs is not accessible by the method. find the index of the element you want to work with and use it by the method mentioned as above.

[Vue.js] Vuex mutations should be function but mutations.default is {}

when trying to fetch data and insert it into a basic html table

<tr>
<td v-for=”item in dataTable” :key=”item.id”>{item.threadName}</td>
</tr>

but when stucking with this error when commiting a mounted function.

mutation.js

import vue.js from ‘vue’

export default {
receiveAll (state, data) {
data.forEach(item => {
return item
})
}
}

this is where when immiting it inside actions.js

import * as api from ‘../api’

export const getData = ({ commit }) => {
api.getData(data => {
commit(‘receiveAll’, data)
})
}

data.js

‘use strict’;

module.export = [
{
id: ‘m_1’,
threadID: ‘t_1’,
threadName: ‘Jing and Bill’,
authorName: ‘Bill’,
text: ‘Hey Jing, want to give a Flux talk at ForwardJS?’,
timestamp: Date.now() - 99999
},
{
id: ‘m_2’,
threadID: ‘t_1’,
threadName: ‘Jing and Bill’,
authorName: ‘Bill’,
text: ‘Seems like a pretty cool conference.’,
timestamp: Date.now() - 89999
}
]

api/index.js

const data = require(‘./data’)
const LATENCY = 16

export function getData (cb) {
setTimeout(() => {
cb(data)
}, LATENCY)
}

and here is the vuex store

import vue.js from ‘vue’
import Vuex from ‘vuex’
import * as actions from ‘./actions’
import * as mutations from ‘./mutations’

Vue.use(Vuex)

const state = {
getData: []
}

export default new Vuex.Store({
state,
actions,
mutations
})

Inside my component, i simply initiating two v-models and the data in computed

<script>
import { mapActions } from ‘vuex’

export default {
name: ‘SearchTable’,
data () {
return {
search_query: ‘’,
search_sort: ‘’
}
},
computed: mapActions({
dataTable: ‘getData’
})
}
</script>

Solution :

Change receiveAll (state, data){ … to function receiveAll (state, data) { …

try this:

import vue.js from ‘vue’

const receiveAll = (state, data) => {
return data.forEach(item => {
return item
})
}

export default {
receiveAll
}

Solution 2:

that’s right mutation is object and it has methods.
it is short form of this example

export default {
receiveAll: function (state, data) {
data.forEach(item => {
state.getData.push(item)
})
}
}

please see Method definitions

you must insert data to state when mutation will happen

export default {
receiveAll (state, data) {
data.forEach(item => {
state.getData.push(item)
})
}
}

[Vue.js] Test scrollbar visible false positive

to test if the document is NOT scrollable, by using

$el = document.documentElement
const noscroll = $el.clientHeight === $el.scrollHeight // false

console.log($el.clientHeight) // 977
console.log($el.scrollHeight) // 991
console.log($el.scrollTop) // 0

But there is no visible scroll bar in the window. Not sure why it’s not working. I also tried this, but no luck.

Put in more context here:

this.getData().then(data => {
this.$nextTick().then(() => {
const $el = document.documentElement
if (!this.isPageEnd && $el.clientHeight - $el.scrollTop === $el.scrollHeight) {
this.getData()
}
})
})

Solution :

The problem is the condition in the following line

const noscroll = $el.clientHeight === $el.scrollHeight << — this line will only return true if both the client height and scroll height are the same.

You need to check if scroll height is less than or equal to client height

Sometimes rubber duck debugging might help

$el = document.documentElement
const hasScroll = $el.scrollHeight <= $el.clientHeight

console.log($el.clientHeight)
console.log($el.scrollHeight)
console.log(hasScroll)
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
height: 1200px;
}

button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}

#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}

#banner-message.alt button {
background: #fff;
color: #000;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=”banner-message”>
<p>A large div</p>

</div>

[Vue.js] How to set timeout while doing vue-cli unit test

when performing vue.js unit through below command

vue-cli-service test:unit

Now the problem is some unit test case need the response from the server, and usually they take much time to execute.

So to know how to manually set the timeout for vue-cli unit tests

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure
“done()” is called; if returning a Promise, ensure it resolves.

Solution :

Try as below

vue-cli-service test:unit –timeout, -t timeout threshold in milliseconds

[Vue.js] laravel vuejs/axios put request Formdata is empty

there is a few application, when when sending formdata using axios post data is successfully sent to API. but when when using put request its not working with formData.

<template>
<div class=”container”>
<div class=”container-fluid” style=”background:#fff”>
<div class=”page-header”>
<h4 class=”page-title”>
<i class=”flaticon-users”></i> Leads
</h4>
<ul class=”breadcrumbs”>
<li class=”nav-home”>
<a href=”/“>
<i class=”flaticon-home”></i>
</a>
</li>
<li class=”separator”>
<i class=”flaticon-right-arrow”></i>
</li>
<li class=”nav-item”>
<router-link to=”/leads”>Leads</router-link>
</li>
<li class=”separator”>
<i class=”flaticon-right-arrow”></i>
</li>
</ul>
</div>
<template>
<div class=”btn-wrapper”>
<button v-on:click=”seen = !seen” class=”btn btn-primary btn-md”>
<i class=”flaticon-interface-1”></i>Add New Lead
</button>
</div>
<p></p>
</template>
<div class=”row”>
<div class=”col-md-12” v-if=”!seen”>
<div class=”card”>
<div class=”card-header”>
<h4 class=”card-title”>
<i class=”flaticon-interface-1”></i> New Leads
</h4>
</div>
<div class=”card-body”>
<form
@submit.prevent=”addLeads”
id=”leadform”
class=”mb-3”
enctype=”multipart/form-data”
\>
<div class=”col-md-12”>
<div class=”row”>
<div class=”col-md-6”>
<label>Lead</label>
<div class=”form-group”>
<input
type=”text”
id=”name”
name=”lead_name”
class=”form-control”
placeholder=”Lead Name”
v-model=”form.name”
\>
<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘name’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>

<div class=”col-md-6”>
<label>Source</label>
<div class=”form-group”>
<textarea
type=”text”
id=”source”
name=”source”
class=”form-control”
placeholder=”lead Souve”
v-model=”form.source”
\></textarea>

<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘source’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
<div class=”row”>
<div class=”col-md-6”>
<label>Value</label>
<div class=”form-group”>
<input
type=”text”
id=”value”
name=”value”
class=”form-control”
placeholder=”lead Value”
v-model=”form.value”
\>

<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘value’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class=”col-md-6”>
<label>Notes</label>
<div class=”form-group”>
<textarea
type=”text”
id=”notes”
name=”notes”
class=”form-control”
placeholder=”lead Notes”
v-model=”form.notes”
\></textarea>

<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘notes’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
<div class=”row”>
<div class=”col-sm-6”>
<div class=”form-group”>
<label for=”exampleFormControlSelect1”>Assigned To</label>
<template v-if=”!userlist”>
<select class=”form-control” id=”assigned_to”>
<option value>No User Found</option>
</select>
</template>
<template v-else>
<select
v-model=”form.assigned_to”
name=”assigned_to”
class=”form-control”
id=”assigned_to”
\>
<option value>Please Select</option>
<option v-for=”user in userlist” :key=”user.id” :value=”user.id”>
<template v-if=”user.id == currentUser.id”>Me</template>
<template v-else>{ user.name }</template>
</option>
</select>
</template>
<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘assigned_to’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class=”col-sm-6”>
<div class=”form-group”>
<label>Close Date</label>
<div class=”clearfix”></div>
<date-picker v-model=”form.date” name=”close_date”></date-picker>
</div>
</div>
</div>
<div class=”row”>
<div class=”col-md-6”>
<label>Email</label>
<div class=”form-group”>
<input
type=”text”
id=”email”
name=”email”
class=”form-control”
placeholder=”User Email”
v-model=”form.email”
\>

<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘email’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class=”col-md-6”>
<label>Phone</label>
<div class=”form-group”>
<input
type=”text”
id=”phone”
name=”phone”
class=”form-control”
placeholder=”User Phone Number”
v-model=”form.phone”
\>

<template v-if=”errors”>
<span v-for=”(fieldsError, fieldName) in errors” :key=”fieldName”>
<template v-if=”fieldName == ‘phone’”>
<p class=”errors”>
<strong>{ fieldsError.join(‘\n’) }</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
</div>
<div class=”row”>
<div class=”col-md-6”>
<div class=”form-group”>
<input
type=”file”
multiple=”multiple”
id=”attachments”
@change=”uploadFieldChange”
\>
<hr>
<div class=”col-md-12”>
<div
class=”attachment-holder animated fadeIn”
v-cloak
v-for=”(attachment, index) in attachments”
\>
<template v-if=”attachment.file_name”>
<span class=”label label-primary”>{ attachment.file_name}</span>
</template>
<template v-else>
<span
class=”label label-primary”
\>{ attachment.name + ‘ (‘ + Number((attachment.size / 1024 / 1024).toFixed(1)) + ‘MB)’}</span>
</template>
<span
class
style=”background: red; cursor: pointer;”
@click=”removeAttachment(attachment)”
\>
<button class=”btn btn-xs btn-danger”>Remove</button>
</span>
</div>
</div>
</div>
</div>
</div>

<div class=”row”>
<div class=”col-sm-6”>
<div class=”form-check”>
<label>Status</label>
<br>
<label class=”form-radio-label”>
<input
class=”form-radio-input”
v-model=”form.status”
type=”radio”
name=”status”
value=”open”
checked
\>
<span class=”form-radio-sign”>Open</span>
</label>
<label class=”form-radio-label ml-3”>
<input
class=”form-radio-input”
v-model=”form.status”
type=”radio”
name=”status”
value=”sent”
\>
<span class=”form-radio-sign”>Proposal Sent</span>
</label>
<label class=”form-radio-label ml-3”>
<input
class=”form-radio-input”
v-model=”form.status”
type=”radio”
name=”status”
value=”won”
\>
<span class=”form-radio-sign”>Won</span>
</label>
<label class=”form-radio-label ml-3”>
<input
class=”form-radio-input”
v-model=”form.status”
type=”radio”
name=”status”
value=”lost”
\>
<span class=”form-radio-sign”>lost</span>
</label>
</div>
</div>
</div>
<div class=”col-md-6”>
<div class=”form-group”>
<button type=”submit” class=”btn btn-success”>Save</button>
<button @click=”clearForm()” class=”btn btn-danger”>Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class=”container-fluid” style=”background:#fff;”>
<kanban-board :stages=”stages” :blocks=”blocks” @update-block=”updateBlock”>
<div v-for=”stage in stages” :slot=”stage”>
<h2>{ stage }</h2>
</div>
<div v-for=”block in blocks” :slot=”block.id”>
<div>
<strong>{ block.name }</strong>
</div>
<p></p>
<button class=”btn btn-danger”>UKDH</button>
<button class=”btn btn-warning”> { block.value }</button>
<router-link :to=”`/account/${block.id}/convert`“ class=”btn btn-primary”>create account</router-link>
<div class=”text-right”>
<router-link :to=”`/leads/${block.id}`“ class=”btn btn-link btn-info”>
<i class=”la la-street-view”></i>
</router-link>

<a href=”#” @click=”deleteLead(block.id)” class=”btn btn-link btn-danger”>
<i class=”la la-times”></i>
</a>
<a href=”#” @click=”editLead(block)” class=”btn btn-link btn-primary”>
<i class=”la la-edit”></i>
</a>
</div>
</div>
</kanban-board>
</div>
</div>
</template>
<script>
import { addLeadsAPI } from “../../helpers/api”;
import { updateStatus } from “../../helpers/api”;
import { getCommonAPI } from “../../helpers/api”;
import { deleteAPI } from “../../helpers/api”;
import validate from “validate.js”;
import DatePicker from “vue2-datepicker”;

export default {
name: “leads”,
components: {
DatePicker
},
data() {
return {
leads: [],
userlist: [],
attachments: [],
percentCompleted: 0,
upload_size: 0,
result: {},
stages: [“open”, “sent”, “lost”, “won”],
blocks: [],
form: {
id: “”,
name: “”,
source: “”,
value: 0,
notes: “”,
user_id: “”,
assigned_to: 1,
date: new Date(),
email: “”,
phone: “”,
status: “”
},
lead_id: “”,
pagination: {},
edit: false,
isOpen: 0,
seen: true,
errors: null
};
},
created() {
this.fetchLeads();
this.getusers();
},
mounted() {
this.$store.dispatch(“leads”);
},
methods: {
getusers(page_url) {
let vm = this;
getCommonAPI(“/users”, “get”, {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: “application/json”
}
}).then(res => {
vm.userlist = res.data;
});
},

fetchLeads(page_url) {
let vm = this;
page_url = page_url || “/leads/lead”;
getCommonAPI(page_url, “get”, {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: “application/json”
}
}).then(res => {
vm.blocks = res.data.data;
//vm.makePagination(res.meta, res.links);
});
},
makePagination(meta, links) {
let pagination = {
current_page: meta.current_page,
last_page: meta.last_page,
next_page_url: links.next,
prev_page_url: links.prev
};
this.pagination = pagination;
},
editLead(form) {
console.log(form);
this.edit = true;
this.seen = false;
this.form.id = form.id;
this.form.name = form.name;
this.form.lead_sid = form.lead_sid;
this.form.status = form.status;
this.form.type = form.type;
this.form.source = form.source;
this.form.value = form.value;
this.form.notes = form.notes;
this.form.email = form.email;
this.form.phone = form.phone;
this.form.assigned_to = form.assigned_to;
this.form.date = form.close_date;
this.attachments = form.uploads;
},
clearForm() {
this.edit = false;
this.form.id = null;
this.form.user_id = null;
this.form.assigned_to = “”;
this.form.type = “”;
this.form.status = true;
this.form.name = “”;
this.form.source = “”;
this.form.value = “”;
this.form.notes = “”;
this.form.email = “”;
this.form.phone = “”;
this.attachments = [];
},
addLeads() {
if (this.edit === false) {
// add new leads
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
// multiple file uploading
this.lead = document.getElementById(“leadform”);
const formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append(“attachments[]“, attachment);
}
}
var config = {
headers: { “Content-Type”: “multipart/form-data” },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
this.$store.dispatch(“lead”);

addLeadsAPI(formData, “post”).then(res => {
swal(“Good job!”, “You clicked the button!”, “success”);
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
} else {
this.errors = null;

const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
console.log(“when in edit”);
// multiple file uploading
this.lead = document.getElementById(“leadform”);
let formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append(“attachments[]“, attachment);
}
}
console.log(formData);
var config = {
headers: { “Content-Type”: “multipart/form-data” },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
console.log(formData);
this.$store.dispatch(“lead”);
//update
addLeadsAPI(formData, “put”).then(res => {
swal(“Good job!”, “You clicked the button!”, “success”);
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
}
},
getConstraints() {
return {
name: {
presence: true,
length: {
minimum: 6,
message: “Must be at least 6 characters long”
}
},
source: {
presence: true,
length: {
minimum: 6,
message: “Must be at least 6 characters long”
}
},
value: {
presence: true,
length: {
minimum: 1,
message: “Must be at least 1 characters long”
}
},
notes: {
presence: true,
length: {
minimum: 6,
message: “Must be at least 6 characters long”
}
}
};
},
updateBlock(id, status) {
//api call axios
updateStatus(id, status, “get”).then(res => {
this.clearForm();
this.fetchLeads();
});
this.blocks.find(b => b.id === Number(id)).status = status;
},
deleteLead(id) {
swal({
title: “Are you sure?”,
text: “Do you really want to delete Lead!”,
type: “warning”,
buttons: {
confirm: {
text: “Yes, delete it!”,
className: “btn btn-success”
},
cancel: {
visible: true,
className: “btn btn-danger”
}
}
}).then(Delete => {
if (Delete) {
deleteAPI(`/lead/${id}`, “delete”, {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: “application/json”
}
}).then(res => {
swal({
title: “Deleted!”,
text: “the lead has been deleted.”,
type: “success”,
buttons: {
confirm: {
className: “btn btn-success”
}
}
});
this.fetchLeads();
});
} else {
this.fetchLeads();
swal.close();
}
});
},
getAttachmentSize() {
this.upload_size = 0; // Reset to beginning
this.attachments.map(item => {
this.upload_size += parseInt(item.size);
});

this.upload_size = Number(this.upload_size.toFixed(1));
this.$forceUpdate();
},

removeAttachment(attachment) {
this.attachments.splice(this.attachments.indexOf(attachment), 1);

this.getAttachmentSize();
},
// This function will be called every time you add a file
uploadFieldChange(e) {
console.log(this.attachments);
var files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
for (var i = files.length - 1; i >= 0; i–) {
this.attachments.push(files[i]);
}
console.log(“out”);
// Reset the form to avoid copying these files multiple times into this.attachments
document.getElementById(“attachments”).value = [];
}
},
computed: {
users() {
return this.$store.getters.users;
},

currentUser() {
return this.$store.getters.currentUser;
}
}
};
</script>
<style lang=”scss”>
@import “../assets/board.scss”;
</style>
<style scoped>
.vue-js-switch#changed-font {
font-size: 30px;
}
.hide {
display: none;
}
.errors {
color: lightcoral;
border-radius: 5px;
padding: 21px 0 2px 0;
}
</style>

when edit option true. when calling method addLeadsAPI for posting data with axios put but Formdata is empty $request->all().

Anyone can help me with this?seems axios put is not working for editing data. through formdata.

Solution :

It may be related to this, https://laravel.com/docs/5.0/routing#method-spoofing.
when using PUT, PATCH or DELETE, you may need to also let laravel know the form method you are using. Try adding “_method” property with the value “PUT”, and let me know if that works for you

Solution 2:

Laravel can not handle multipart-formdata well with PUT method. See Input from PUT requests sent as multipart/form-data is unavailable #13457.

If the code actually uses the PUT method, it seems to be affected by this problem.

There are several workarounds.

Dealing with the client side:

Instead of PUT method, use POST method with _method parameter value set to PUT (called ‘method spoofing’)

Dealing with the server side:

Add a package that performs multipart processing to Laravel. (ex. illuminatech/multipart-middleware)
Use pecl/apfd extension which provides ability to parse ‘multipart/form-data’ HTTP requests for any request method.

Solution 3:

there is changed the axioscall into post and set the value _method:put

addLeads() {
if (this.edit === false) {
// add new leads
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
// multiple file uploading
this.lead = document.getElementById(“leadform”);
const formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append(“attachments[]“, attachment);
}
}
var config = {
headers: { “Content-Type”: “multipart/form-data” },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
this.$store.dispatch(“lead”);
formData.append(“_method”, “post”);
addLeadsAPI(formData, “post”, config).then(res => {
swal(“Good job!”, “You clicked the button!”, “success”);
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
} else {
this.errors = null;

const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
console.log(“when in edit”);
// multiple file uploading
this.lead = document.getElementById(“leadform”);
let formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append(“attachments[]“, attachment);
}
}
formData.append(“_method”, “put”);
formData.append(“id”, this.form.id);
console.log(formData);
var config = {
headers: { “Content-Type”: “application/x-www-form-urlencoded” },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
console.log(formData);
this.$store.dispatch(“lead”);
//update
addLeadsAPI(formData, “put”, config).then(res => {
swal(“Good job!”, “You clicked the button!”, “success”);
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
}
},

[Vue.js] PHP not parsing JSON as i want it

there is a hobby project that provides an api to access, everything works fine on other ends, the thing is that i need the json array to not have brackets so i can separate the object in the array.

This is the url that provided the json :
https://cryptoapi.news/api/v1/free/lastnews/all/10

But if you look at this api for example :
https://api.coindesk.com/v1/bpi/currentprice.json

it has no brackets in the object, that [] brackets before article array are stoping me from acessing the object in vue.js

when pushing on my api end point this elements to an empty array :

$json = array(
“article” => array(
“article_id” => “$idx”,
“article_title” => “$title”,
“article_content” => “$content”,
“article_date” => “$date”,
“article_image” => “$image”,
“article_coin” => “$coinx”,
“article_source” => $src
));

array_push($main, $json);

//$json = array_values($json);

then providing the json as this :

$js = json_encode($main, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
print_r($js);

I just need to remove that brackets and it ill make the object acessible

Solution :

If you don’t want the object you create to be in an array, then don’t put it in an array!.

Remove array_push($main, $json);, then json_encode the $json variable.