link411 link412 link413 link414 link415 link416 link417 link418 link419 link420 link421 link422 link423 link424 link425 link426 link427 link428 link429 link430 link431 link432 link433 link434 link435 link436 link437 link438 link439 link440 link441 link442 link443 link444 link445 link446 link447 link448 link449 link450 link451 link452 link453 link454 link455 link456 link457 link458 link459 link460 link461 link462 link463 link464 link465 link466 link467 link468 link469 link470 link471 link472 link473 link474 link475 link476 link477 link478 link479 link480 link481 link482 link483 link484 link485 link486 link487 link488 link489 link490 link491 link492 link493 link494 link495 link496 link497 link498 link499 link500 link501 link502 link503 link504 link505 link506 link507 link508 link509 link510 link511 link512 link513 link514 link515 link516 link517 link518 link519 link520 link521 link522 link523 link524 link525 link526 link527 link528 link529 link530 link531 link532 link533 link534 link535 link536 link537 link538 link539 link540 link541 link542 link543 link544 link545 link546 link547

[Vue.js] Vue.js conditional if else Subscribe to RSS

need some help, thanks.

I don’t know how to write the proper condition in vue.js for my task.

i got those 2 values

content.Image &
header.Background

Basically what to do is to check if there is a jpeg to content.Image assigned as background-image then use this image as background, else use the jpeg that is assigned in header.Background.

:style=”{‘background-image’: ($_.isEmpty(content.Image) ? ‘’ :
‘url(‘+_CONFIG.media_url + content.Image +’)’) }”>

thats as far as i could get some kind of if-else condition but i dont have any clue how to properly write the code for it.

Solution :

try using computed property to provide boolean:


:style=”[this.imageTest == true ? {} :
{‘url(‘+_CONFIG.media_url + content.Image +’)’) }]“


computed: {
imageTest () {
if (document.getElementById(‘idOfBackgroundImage’) === $_.isEmpty(content.Image)) {
return true;
} else {
return false;
}
}
}

[Vue.js] Send data in variable (not on form submit) to google sheet Subscribe to RSS

when new to Vue.js and to javascript. when trying to send some data to a google sheet without success.

there is found some info on how to post data, but my data is not stored in a form. So there is appended an empty ‘form’ with the data to post without luck.

This is the source:
https://github.com/jamiewilson/form-to-google-sheets
and:
Is it possible to send js variables to google sheets? (Not form data)

This is how I post the data:

saveToGoogleSheet () {
const scriptURL = ‘https://script.google.com/macros/s/…/exec'
const form = ‘’
var sendingData = new FormData(form)
sendingData.append(‘starRating’, this.feedbackData.starRating)

fetch(scriptURL, {method: ‘POST’, body: new FormData(sendingData)})
.then(response => console.log(‘Success!’, response))
.catch(error => console.error(‘Error!’, error.message))
}

this is the google script

var sheetName = ‘Sheet1’
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty(‘key’, activeSpreadsheet.getId())
}

function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)

try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty(‘key’))
var sheet = doc.getSheetByName(sheetName)

var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1

var newRow = headers.map(function(header) {
return header === ‘timestamp’ ? new Date() : e.parameter[header]
})

sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

return ContentService
.createTextOutput(JSON.stringify({ ‘result’: ‘success’, ‘row’: nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}

catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ ‘result’: ‘error’, ‘error’: e }))
.setMimeType(ContentService.MimeType.JSON)
}

finally {
lock.releaseLock()
}
}

After running my app, I receive a success message:

Success!
Response{type: “cors”, url: “https://script.googleusercontent.com/macros/echo?uxxx", redirected: true, status: 200, ok: true,}
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: true
status: 200
statusText: “”
type: “cors”
url: “https://script.googleusercontent.com/macros/echo?user\_content\_key=…"
__proto__: Response

but the google spreadsheet do not get populated, and yet the data exist if I console.log it.

1) What am I doing wrong?

2) Also, is there a way to send the data without appending an empty form?

3) Finally, what if to send more data, can I do something like

sendingData.append({
‘starRating’ = this.feedbackData.starRating
‘nowReading’ = this.feedbackData.nowReading
})

or do I need to do:

sendingData.append(‘starRating’, this.feedbackData.starRating)
sendingData.append(‘nowReading’, this.feedbackData.nowReading)

or what?

-- UPDATE –

after posting the question I decided to start afresh with Google Sheet. the result is that now I do post data to the sheet, but it is ‘undefined’ despite the data is there before and after the posting:

console.log(this.feedbackData)
this.saveToGoogleSheet()
console.log(this.feedbackData)

there is tried the single variable as per above, or posting all the variables at once (most of which were ‘undefined’ at the time of posting) like this:

saveToGoogleSheet () {
const scriptURL = ‘https://script.google.com/macros/s/…/exec'
fetch(scriptURL, {method: ‘POST’, body: JSON.stringify(this.feedbackData)})
.then(response => console.log(‘Success!’, response))
.catch(error => console.error(‘Error!’, error.message))
}

and like this:

saveToGoogleSheet () {
const scriptURL = ‘https://script.google.com/macros/s/…/exec'
fetch(scriptURL, {method: ‘POST’, body: this.feedbackData})
.then(response => console.log(‘Success!’, response))
.catch(error => console.error(‘Error!’, error.message))
}

but the result is the same.

My JSON.stringify(this.feedbackData) looks like this:

{“userName”:””,”userNumber”:””,”friendName”:””,”friendNumber”:””,”inviteMessage”:””,”nowReading”:”S2/E1/“,”starRating”:”4”}

Solution :

You have already deployed Web Apps for accepting value.
You want to put the values to the Spreadsheet like the below image by sending the object of {“userName”:””,”userNumber”:””,”friendName”:””,”friendNumber”:””,”inviteMessage”:””,”nowReading”:”S2/E1/“,”starRating”:”4”} with fetch() of Javascript.

If my understanding is correct, how about this modification?

Modification points:

When the value is sent using POST method, the value can be retrieved with e.postData.contents from e of doPost(e).

But in this case, the value is required to be sent as a string. So please use JSON.parse().
So please use body: JSON.stringify(this.feedbackData)} at fetch() side.

Modified script:

Please modify as follows.

Google Apps Script:

From:

var newRow = headers.map(function(header) {
return header === ‘timestamp’ ? new Date() : e.parameter[header]
})

To:

var params = JSON.parse(e.postData.contents); // Added
var newRow = headers.map(function(header) {
return header === ‘timestamp’ ? new Date() : params[header]; // Modified
});

Javascript:

Please use the above script of “UPDATE” section in the question.

saveToGoogleSheet () {
const scriptURL = ‘https://script.google.com/macros/s/…/exec'
fetch(scriptURL, {method: ‘POST’, body: JSON.stringify(this.feedbackData)})
.then(response => console.log(‘Success!’, response))
.catch(error => console.error(‘Error!’, error.message))
}

Note:

When you modified the Google Apps Script of Web Apps, please deploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
I’m not sure about the actual Spreadsheet. If it is different from the above image, please modify the script for the situation.

References:

Web Apps
Taking advantage of Web Apps with Google Apps Script

If I misunderstood the question and this was not the result you want, I apologize.

Solution 2:

there is found the problem:

in here:

saveToGoogleSheet () {
const scriptURL = ‘https://script.google.com/macros/s/…/exec'
const form = ‘’
var sendingData = new FormData(form)
sendingData.append(‘starRating’, this.feedbackData.starRating)

fetch(scriptURL, {method: ‘POST’, body: new FormData(sendingData)})
.then(response => console.log(‘Success!’, response))
.catch(error => console.error(‘Error!’, error.message))
}

I should change this:

fetch(scriptURL, {method: ‘POST’, body: new FormData(sendingData)})

into this:

fetch(scriptURL, {method: ‘POST’, body: sendingData})

Also, I don’t need const form = ‘’ if I put var sendingData = new FormData(‘’)

[Vue.js] How write a JSON object in a file Subscribe to RSS

there is a JSON object which is a list of elements, each elements is an array that contains: Name, Id and Quantity. Having already the JSON object saved on the servlet, I just have to take it and write it through writer.write to a .txt file.

ArrayList<EntryList> al = new ArrayList<>();

public void inserisci(@RequestBody EntryList item)
{
item.setId(al.size());
item.setQuantity(item.getQuantity());

al.add(item);

try {
FileWriter writer = new FileWriter(“/file.txt”);

for (EntryList el : al)
{
writer.write(el.toString());
}

}
writer.close();

catch (Exception e) {

}

But this way it just writes the name of the element. How can I solve it?

Solution :

Please use this :-

String lineSeparator = System.getProperty(“line.separator”);
FileOutputStream fos = null;
String s = json file;
File file = new File(“file path “);
fos = new FileOutputStream(file, true);
fos.write(lineSeparator.getBytes());
fos.write(s.getBytes());
fos.flush();

[Vue.js] variable is not updating in vue js, showing variable is not defined Subscribe to RSS

when trying to bind the updated value of totalQuestions variable in the html. but it is showing below error. can anyone tell me where i did wrong.

HTML

<label><span class=”red-text”>Question No: </span><span>1 out of {totalQuestions}</span>/</label>

Variable:

date() {
return {
examKey: ‘’,
questionsIds: ‘’,
duration: 0,
questionList: [],
totalQuestions: ‘’
}
},

Methods

methods: {
loadQuestionSet: function() {
this.examKey = this.$route.params.key;
this.$http.get(baseUrl.BASE_URL + ‘question-set/key/‘ + this.examKey).then(
(resp) => {
this.duration = resp.data.duration;
this.questionsIds = resp.data.questionIds;
this.loadQuestions();
},
(err) => {
this.$router.push(“/exam”);
}
);
},

loadQuestions: function() {
this.$http.post(baseUrl.BASE_URL + ‘question/exam/questions’, this.questionsIds).then(
(resp) => {
this.questionList = resp.data;
this.totalQuestions = this.questionList.length
},
(err) => {
console.log(err);
}
);
}
},
beforeMount: function() {
this.loadQuestionSet();
}

Solution :

You have a typo: date() should be data().

[Vue.js] VueJS 2 - Default click event on component Subscribe to RSS

Is it possible in VueJS to have a default click event on a custom component?

E.g. we have built a component called editable. Now on click, we always want it to fire the same function, no matter where we call that component.

<editable @click=”doSomething” …></editable>

Can I define that somewhere in the JS side?

Solution :

In case of custom component, you need to bind to native event:

<editable @click.native=”doSomething” …></editable>

For documentation, refer to Vue.js docs here.

[Vue.js] How to wait for user enter in vue input with v-model Subscribe to RSS

Code:

<input type = “number” min=”10” max=”90” value=”50” v-model=”preview_width”/>

My website changes width of 2 components depending on “preview_width value”. When I change value in input, website moves and doesn’t let user enter correct value in friendly way. And my question is: How to edit “preview_value” AFTER user press “Enter”, or after he stop targeting this input?

Solution :

You could use lazy to update the v-model only on change.

<input type = “number” min=”10” max=”90” value=”50” v-model.lazy=”preview_width”/>

or

<input type = “number” min=”10” max=”90” value=”50” v-model=”preview_width” lazy/>

Here is the doc: https://v1.vuejs.org/guide/forms.html#lazy

Solution 2:

You can use lodash debounce method, which will delay triggering of the method to update width.

<input v-on:input=”onChangePreviewWidth”>

methods: {
onChangePreviewWidth: _.debounce(function (e) {
this.preview_width = e.target.value;
}, 500)
}

Solution 3:

v-model has a .lazy modifier, which will sync the data after change events:

<input type = “number” min=”10” max=”90” value=”50” v-model.lazy=”preview_width”/>

You can read the documentation here: https://vuejs.org/v2/guide/forms.html#lazy

[Vue.js] Error in v-on handler ReferenceError assignment to undeclared variable order Subscribe to RSS

I use Laravel as an api, there is pass a collection (orders) of object (order) at the view.
I don’t no why I can’t access to my variable in a simple methods in vue.js ..

props: [‘orders’],
mounted() {
console.log(‘Component mounted.’);
},
data() {
return {
select: [],
selected: ‘csv’,
options: [
{ text: ‘Export CSV’, value: ‘csv’ },
{ text: ‘Factures PDF’, value: ‘pdf’ },
{ text: ‘Changer de status’, value: ‘status’ },
],
status: ‘1’,
orders: this.orders,
}
},

methods: {
submit() {
if (this.selected == ‘csv’) {
// faire csv
} else if (this.selected == ‘pdf’){
// faire pdf
} else {
for (order in this.orders) {
console.log(order.id);
}

axios.post(‘/api/admin/commandes/change-status’,{
newStatus:this.status,
select:this.select
}).then(function (response) {
console.log(response);
})
}
}
},

error : [vue.js warn]: Error in v-on handler: “ReferenceError: orders is not defined”

The problem is just un the for..in because I can display Orders in the view.

Solution :

Props, data properties and computed properties all need to have unique names. All three are typically accessed via this.blah (where blah is the name) so if you have two with the same name you’ll have difficulty referring to the correct one.

In the case you’ve got a prop called orders and a data property called orders. If you need both then they’ll need to have different names but if they’re just going to have the same value then there’s no need to have both. Based on the code you’ve posted it would seem that you just need the prop and can remove the data property.

None of which really explains the error messages you reported, but it is a problem you should fix before going any further.

There are a couple of problems with this line:

for (order in this.orders)

Firstly, you need a var, let or const to declare order, otherwise it’ll end up being global. I’d suggest const unless you’ve got a good reason to use something else.

I believe that would explain the error message you posted in the title.

Secondly, using for/in will iterate over the keys of the object/array. It’s unlikely that’s what you want as order will be the property name/index and not the value itself. Given you’re trying to access order.id I would guess you meant to use for/of instead?

I struggle to explain what would cause the second error message you posted. I had initially thought it could be because this.orders was undefined but I don’t believe that would cause such a message in the code you posted.

[Vue.js] How to pass html code in url query string Subscribe to RSS

I need to pass a html message through url query string. But when getting error. there is tried encodeURIComponent() , encodeURI(), escape()

var uriMessage = encodeURIComponent(“<p>This is my test message..</p>”);
window.open(“/controller/action?param=” + uriMessage, “_blank”);

Any help will be really appreciated.

Solution :

You don’t need to encode html somehow, the simple window.open should work. Without knowing what error do you receive it is pretty hard to tell what do you issue.
Also please take a note that the maximum request length for GET requests are pretty short, as you can see in this post, so sending raw html in a query string does not look like a clean solution.

[Vue.js] Vuex doen't update Vue computed property Subscribe to RSS

I’m trying to use vuex as a layer between firestore and my vue.js application.
My vuex store looks like this:

const store = new Vuex.Store({
state: {
posts: [],
},

mutations: {
add_post(state, post) {
state.posts[post.id] = post;
},
},

actions: {
async load_post(context, id) {
let post = await db
.collection(‘posts’)
.where(‘post_id’, ‘==’, id)
.get();
post = post.docs[0];

post = {id, …post.data()};
context.commit(‘add_post’, post);
},
}
});

And inside my vue.js component:

export default {
name: ‘Post’,
beforeMount() {
const id = this.$route.params.id;
this.$store.dispatch(‘load_post’, id);
},
data() {
return {
id: this.$route.params.id
};
},
computed: {
content() {
return this.$store.state.posts[this.id];
}
}
};

Now, when navigating the website, the code seems to run fine. However, if I refresh the page then the content property becomes undefined. After some debugging, I’ve come to the conclusion that it tries to read from the store while loading(therefore being undefined), but when the store is ready nothing updates.
So far I’ve tried watchers, vuex’s mapState, nothing seems to work… any suggestions?

Solution :

vue.js cannot detect a change on a nested property, which is not set in state on load. Try changing the mutation to this:

add_post(state, post) {
Vue.set(state.posts, post.id, post);
}

// You need to import vue.js at the top of the store file, when using the Vue.set() method
import vue.js from ‘vue’;

Solution 2:

It’s vue.js reactivity problem. You should modify state.posts in vuex to make component reactive. Mutate state.posts[post.id] only will not make component reactive, because state.posts still point to old reference.

mutations: {
add_post(state, post) {
state.posts = {
…state.posts,
[post.id]: post
}
},
},

or you can use JSON.parse(JSON.stringify())

add_post(state, post) {
state.posts[post.id] = post;
state.posts = JSON.parse(JSON.stringify(state.posts))
},

[Vue.js] The browser overwrites the content of the message after receiving the response Subscribe to RSS

there is a little problem with DingoAPI and Vue.js when I’m trying to get my error message from response. I think the browser is replacing my custom message by the default one. Here is my code:

PHP script

if($request->readerId){
Return succes (this works properly)
else{
return $this->response->error(
‘No reader’,
400 //(or diffrent code)
);
}

Vue.js script

await axios.post(API_URL + ‘card/‘, {
some data
}, {
headers: {
headers
},
}).then(({data}) => {
context.commit(SET_RESPONSE, data);
}).catch((error) => {
console.log(error.message);
throw error
})

When I’m trying to look on my message in the network tab I can see (so DingoAPI did it correctly):

{“message”:”No reader”,”status_code”:400}

But when I’m using console.log(error.message) or trying to show it on the page there is standard error message:

Request failed with status code 400

Is there a way to set error message with DingoAPI and catch it in my .js script?
Maybe I need to write my own custom exception?

Solution :

What you want is access to the data of the response from the error variable.

console.log(error.response.data.message); // No reader

Otherwise you can log error.response to see the object:

console.log(error.response);

If you wonder why it’s printing Request failed with status code 400:

The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.

Source: https://github.com/axios/axios/issues/960#issuecomment-309287911