link1370 link1371 link1372 link1373 link1374 link1375 link1376 link1377 link1378 link1379 link1380 link1381 link1382 link1383 link1384 link1385 link1386 link1387 link1388 link1389 link1390 link1391 link1392 link1393 link1394 link1395 link1396 link1397 link1398 link1399 link1400 link1401 link1402 link1403 link1404 link1405 link1406 link1407 link1408 link1409 link1410 link1411 link1412 link1413 link1414 link1415 link1416 link1417 link1418 link1419 link1420 link1421 link1422 link1423 link1424 link1425 link1426 link1427 link1428 link1429 link1430 link1431 link1432 link1433 link1434 link1435 link1436 link1437 link1438 link1439 link1440 link1441 link1442 link1443 link1444 link1445 link1446 link1447 link1448 link1449 link1450 link1451 link1452 link1453 link1454 link1455 link1456 link1457 link1458 link1459 link1460 link1461 link1462 link1463 link1464 link1465 link1466 link1467 link1468 link1469 link1470 link1471 link1472 link1473 link1474 link1475 link1476 link1477 link1478 link1479 link1480 link1481 link1482 link1483 link1484 link1485 link1486 link1487 link1488 link1489 link1490 link1491 link1492 link1493 link1494 link1495 link1496 link1497 link1498 link1499 link1500 link1501 link1502 link1503 link1504 link1505 link1506

[Vue.js] Conditional formatting on BootstrapVue <b-form-select>?

there is a <b-form-input> in my vue.js component. there is the :options set to an array of email addresses.

This is the list of email addresses that the user can start a chat with. The method i use to get these email addresses, i can’t really stop the <b-input-select> from having the currently logged in users email address in it.

This is a problem because obviously a user shouldn’t be able to start a chat with themself.

Is there a way to conditionally render these :options based on if they’re not equal to the email address of the currently signed in user?

The tag i currently have is this:

<b-form-select :options=”usersNotChatting” v-model=”newChat.participants[1].userEmail”></b-form-select>

Thanks.

Solution :

You can use the computed property for filtering option data.

computed:{
getoption(){
let filtered_option = this.mail_list.filter(function(item){
return item.value!='Test2@gmail.com‘ // currently signed user email
})
return filtered_option;
}
}

<b-form-select id=”exampleInput3”
:options=”getoption”
required
v-model=”newChat.participants[1].userEmail”>
</b-form-select>

[Vue.js] node.js, vue.js and express.js stack development

when trying to create a web app using vue.js, express.js and node.js using the Visual Studio Code IDE on Linux. Following some documentation online, there is read that after installing vue.js, one can create a vue.js app using the following command:

vue.js create my-app

Following other documentation, it is stated that one can create an express.js app by executing this command:

express myExpressApp

How can I create an app, that I will be developing using the VS Code IDE that is both a vue.js app and an express.js app?

Solution :

I would recommend creating the vue.js app first. The add in the Express stuff manually, because that bit is quick and easy.

1. Start by creating the vue.js app

If you follow the vue.js documentation here, using the vue-cli it will structure everything for you

The contents of the vue.js source will live inside the src directory in the project root. Once you’ve run npm run build (same as vue-cli-service build) a dist directory will be created, containing the built client-side code.

2. Add in Express

I’d recommend putting the server side code in a new directory in the project root, say server, then create a file in that dir, and add in the below code…

const express = require(‘express’);
const history = require(‘connect-history-api-fallback’);
const path = require(‘path’);

require(‘dotenv’).config()

const app = express();

const port = process.env.PORT || 8080;

// Serve up built vue.js app, at the main root
const staticFileMiddleware = express.static(path.join(‘dist’));
app.use(staticFileMiddleware);
app.use(history({
disableDotRule: true,
verbose: true
}));
app.use(staticFileMiddleware);

// Make all public assets available
app.use(‘/public’, express.static(‘public’))

// App has started
app.listen(port, () =>
console.log(`Awesome app has started and is running on port ${port} `)
);

There are a couple of dependencies you will need, for the above sample you’ll have to yarn add express connect-history-api-fallback dotenv (or use npm).

express is obviously needed
connect-history-api-fallback dotenv is needed if the using history mode in vue, it is required to not get a 404 on every sub-page.
And dotenv, is just a nice-to-have to read constants from the .env file, which you should also create

Finally to run it, type node server/main (or whatever you called that file in the server dir).

You will probably want to add that command to the package.json..

“scripts”: {
“start”: “node server/main”,

If the using Heroku, double check all the dependencies are correct in the package.json, then create a file called Procfile in the root, containing the following web: node ./server/main.js (or whatever the server file was called), and boom, the vue.js app is now an Express vue.js app, and ready for deploy!

Source: I’ve done this setup a lot of times for my own sites.

[Vue.js] Getting error {detail Method GET not allowed.}

when new to vue.js and django also,
Need some help on below issue.
there is created an api in which when trying to fetch the data from one DB table and send the same to vue.js page to have check on it.

when getting error “{“detail”:”Method \“GET\“ not allowed.”}”

I tried it in multiple ways like sending the data in JSON form or as a array but still getting the same issuse

Model.py below are the models for deserializing and for the table when using to fetch the data

def deserialize_Issue(issue):
“””Deserialize user instance to JSON.”””
return {id’: issue.id, ‘IName’: issue.IName, ‘IDesc’: issue.IDesc, ‘ITeam’: issue.ITeam,’IStat’: issue.IStat, ‘IChat’: issue.IChat, ‘Iuri’: issue.Iuri, ‘Ibridge’: issue.Ibridge, ‘Ibridgedetails’: issue.Ibridgedetails }

class Issue(TrackableDateModel):
IName=models.CharField(max_length=500)
IDesc=models.CharField(max_length=1000)
ITeam =models.CharField(max_length=500)
IStat=models.CharField(max_length=250)
IChat=models.CharField(max_length=2,default=’NA’)
Iuri=models.URLField(default=’NA’)
Ibridge=models.CharField(max_length=2,default=’NA’)
Ibridgedetails=models.CharField(max_length=20,default=’NA’)

def __str__(self):
return self.IName, self.IStat

IN my view.py file there is created the calls and the get method to fetch the data from the table.

class IssuesDetailsView(APIView):

def get(self, request, *args, **kwargs):
DETAILS=’Issue.objects.all()’
serializer=deserialize_Issue(DETAILS,many=True)

return Response ({‘Issues’: serializer.data})

abc.vue.js in vue.js file trying to acees the get the data

fetchIssueDetails () {
\$.get(`http://127.0.0.1:8000/api/chats/\`, (data) => {
this.Issues = data.Issues
})

.fail((response) => {
alert(response.responseText)
})
}

to read the table data in the vue.js file in for loop

Solution :

Here’s the urls.py you’ve provided me in the comments:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
path(‘chats/‘, views.ChatSessionView.as_view()),
path(‘chats/<uri>/‘, views.ChatSessionView.as_view()),
path(‘chats/<uri>/messages/‘, views.ChatSessionMessageView.as_view()),
]

Notice how the url /api/chats/ is tied to views.ChatSessionView, not IssuesDetailsView. Yet in the Javascript you are making the request to /api/chats/.

So one way to resolve the issue is

path(‘chats/‘, views.IssuesDetailsView.as_view()),

[Vue.js] App Engine app.yaml handlers not working as expected

when trying to set up a vue.js application with the vue.js router set in “history” mode. I also want to serve my back end APIs from the same app engine application. (e.g., if a user navigates to /some/path/in/the/app and refreshes the page or shares the link, the application will display the expected page)

here is my app.yaml:

runtime: python37

handlers:
- url: /api/.*
secure: always
script: auto

- url: /css
static_dir: www/css

- url: /js
static_dir: www/js

- url: /semantic
static_dir: www/semantic

- url: /img
static_dir: www/img

- url: /
static_files: www/index.html
upload: www/index.html

- url: /.*
static_files: www/index.html
upload: www/index.html

When I try to hit any of my api endpoints, the static index.html file is served instead of the response from the endpoint.

If the last route is omitted (url: /.*), then the api endpoints are served correctly, but the Vue.js app can only be entered from the “/“ route and the deep links in the application do not work as expected

when not looking to have a script in my application to serve the a static file.

note, this question is similar, but none of the answers addressed my situation:

AppEngine app.yaml config for single page apps

Solution :

The trick was to follow a microservice architecture and split my application into two modules and define the routes in a dispatch.yaml file.

There is a sample project here:

App Engine Modules sample project

[Vue.js] Get totalsum from @onclick in vue

to make the {total} update when I click @addToChart button and it gets the game price from the vue.js array.

HTML:

<p> Total Price: { total } USD</p>
<button @click=”addToChart” :disabled=”!game.inStock”
:class=”{ disabledButton: !game.inStock }”>
Add to Chart
</button>

Vue:

el: “#app”,
data: {
title: “”,
about: “”,
games: [{
id: 0,
title: “”,
inStock: true,
price: 59,

},
{
id: 1,
title: “”,
inStock: true,
price: 40,

},
methods: {
addToChart: function () {
this.cart += 1;
return total;
}

Solution :

You need to define the total property in the data first.
Then just pass the price as argument of the addToCart function.

new Vue({
el: “#app”,
data: {
title: “”,
about: “”,
games: [
{ id: 0, title: “Game 1”, inStock: true, price: 59 },
{ id: 1, title: “Game 2”, inStock: true, price: 40 }
],
total: 0
},
methods: {
addToChart: function (price) {
this.total += price
}
}
})
<script src=”https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<div id=”app”>
<p> Total Price: { total } USD</p>
<div v-for=”game in games”>
{ game.title }
<button @click=”addToChart(game.price)” :disabled=”!game.inStock”>Add to Chart</button>
</div>
</div>

[Vue.js] Mapping a promise which returns foo, to another promise which returns bar?

there is a function which makes an XMLHttpRequest and returns a promise with the response from the request.

However I’d like to instead return a promise which contains just one string from the response.

E.g instead of the promise resolving to response = {status, data} etc, I’d like to return just response.data.some_field

How can I do this?

Solution :

If you call .then on a promise, you’ll produce another promise which will resolve to whatever you return in the callback function. So take the current promise that you’re creating, and then add on the following:

.then((response) => {
return response.data.some_field;
});

So maybe the full function will look like this:

function getStuff() {
return new Promise((resolve, reject) => {
//somethingWithXMLHttpRequest
}).then((response) => {
return response.data.some_field;
});
}

Solution 2:

What you’re looking for is promise chaining. Link goes to mozilla’s doc page on promise chaining.

function httpRequestAsync () {
// Return a promise… This is where the XMLHttpRequest takes place
}

function getStuffAsync() {

// Make the http request, chain the return promise,
// and return a promise, which resolves to the chosen field.
return httpRequestAsync() //Calling .then() on this promise is promise chaining.
.then((response) => {
return response.data.some_field;
});
}

function someBusinessLogicFunction () {

let yourString = “”;

getStuffAsync()
.then((response) => {
yourString = response; // yourString does in fact equal the response param… :).catch(() => {
console.log(“Something went wrong, or this answer sucks ha ha!”);
});
})
}

// Or using async/await, for fun

async someBusinessLogicFunction2 () {

let yourString = “”;

try {
yourString = await getStuffAsync();
} catch (e) {
console.log(“Something went wrong, or this answer sucks ha ha!”);
}
}

My example splits out the HTTP request into one function, with another function declared, which calls that function, and performs the promise chaining. You could omit the second function, and return the chained promise from the function that performs the HTTP request.

Solution 3:

You have something like this (got it from the code block before you edited the question)

const promise = axios
.post(url(“fistbump”), data)
.then(result => {
window.console.log(“Got fistbump response: “, result.data);
localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
});

return promise;

If the Axios promise respects the ES6 promise spec, you can simply return what you want from the .then clause to get the value wrapped in a promise, which gives you

const promise = axios
.post(url(“fistbump”), data)
.then(result => {
window.console.log(“Got fistbump response: “, result.data);
localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
return result.data;
});

return promise;

Solution 4:

Just return a promise that will resolve to the field:

return new Promise(function(resolve, reject) {
axios.post(url(someURL), data)
.then(result => {
resolve(result.data.some_field);
});
});

[Vue.js] Angular right way to show loading for different components at the same time?

In angular 7+ web-app there is a page, on this page, there is 3 different components, I make 3 different HTTP requests in ngOnInit() to calculate components inputs. and while when making requests to show loading spinners for each component.

My current solution is, there is some other component called loading-component, this loading component takes 1 boolean input variable, and if loading is true it overlays loading spinner on components inside it. For my page where there is 3 different components, HTML looks like this:

<div>
<loading-component [loading]=”loadingcomponent1”>
<component1 [input1]=”input1”></component1>
</loading-component>
<loading-component [loading]=”loadingcomponent2”>
<component2 [input2]=”input2”></component2>
</loading-component>
<loading-component [loading]=”loadingcomponent3”>
<component3 [input3]=”input3”></component3>
</loading-component>
</div>

component.ts:

loading1: false;
loading2: false;
loading3: false;
input1: null
input2: null
input3: null

ngOnInit() {
this.loading1 = true;
this.http.get(url1).subscribe(resp => {
this.input1 = resp
this.loading1 = false
})

this.loading2 = true;
this.http.get(url2).subscribe(resp => {
this.input2 = resp
this.loading2 = false
})

this.loading3 = true;
this.http.get(url3).subscribe(resp => {
this.input3 = resp
this.loading3 = false
})
}

I compute 3 different boolean variables for 3 different loading-component. Set true before HTTP request, set false after the response.

My question: Is it a good way or is there any other way (better) to handle this?

ps. In my previous project, which was made with vue.js I used the same strategy

Solution :

I don’t think that it would be that bad. After all you need to keep a flag and a spinner for each component in the case. However it can still be considered as a DRY violation that could easily be fixed with the power of directives.
You can easily create a structural directive that places the spinner depending on the boolean binding you provide.

[Vue.js] Vue changing value of a data property used in v-model doesn't render the newly set value

I’m currently in the process of creating a stepper component using vue.js with Vuex. Each step is a component that holds a input fields. Each step stores the values of the input fields in the Vuex store. When going to a previous step, the already available data should be loaded from the store and displayed in the respective input field.

I’m using a custom input component that implements the v-model directive correctly.

<custom-input v-model=”amount”
v-bind:type=”‘number’”></custom-input>

“amount” is defined in the data function:

data: function () {
return {
amount: null
}
}

Now I’m trying to set the value of the v-model property when the component gets mounted.

mounted() {
this.amount = this.$store.state.fields.amount.value;
}

Through debugging tools I can see that the store holds the correct value. The same is the case for the amount data-property of the component.

I’ve also tried setting the property using the set method like this:

this.$set(this.$data, ‘amount’, this.$store.state.fields.amount.value);

But it still does not show up in the custom-input.

How do I set the data property used in v-model correctly so that it shows up in the input field?

EDIT

The custom-input component is implemented like this:

<input type=”‘text’” v-on:input=”onInput”>

onInput: function (event) {
this.$emit(‘input’, event.target.value);
}

Solution :

The problem was that I did not actually bind the value property within the custom-input component. Adding this fixed the problem:

<custom-input … :value=”value” />

[Vue.js] Change component state form another component rendered in a v-for

there is a list of componnents rendered ina a v-for. to set the “show” boolean property as false in the other components when one of them is set to true:
To simplify when only adding two components

Main component code:

<template>
<aside class=”main-sidebar”>
<section class=”sidebar”>
<ul class=”sidebar-menu” data-widget=”tree”>
<nav-bar-user-profile-item></nav-bar-user-profile-item>
<nav-bar-item></nav-bar-item>
<nav-bar-item></nav-bar-item>
</ul>
</section>
</aside>
</template>

<script>
import NavBarUserProfileItem from ‘@/components/NavBar/NavBarUserProfileItem’;
import NavBarItem from ‘@/components/NavBar/NavBarItem’;

export default {
name: ‘NavBar’,
components: {
NavBarUserProfileItem,
NavBarItem
},
methods: {
MenuHasBeenToggled(event) {
console.log(event);
}
}
}

NavBarItemComponent

<template>
<li class=”treeview2 item” :class=”{‘menu-open’: isOpen, ‘active’: menu.active}” @click=”ToggleState”>
<a href=”#”>
<i class=”fa fa-th”></i>
<span>{ menu.title }</span>
<span class=”pull-right-container”>
<i class=”fa fa-angle-right pull-right”></i>
</span>
</a>
<collapse-transition>
<ul class=”treeview-menu” v-show=”isOpen”>
<li v-for=”submenu in menu.submenus” :key=”submenu.title” :class=”{‘active’: ((‘active’ in submenu) ? submenu.active : false)}”>
<b-link :href=”submenu.link”>
<i class=”fa fa-circle-thin”></i>
{ submenu.title }
</b-link>
</li>
</ul>
</collapse-transition>
</li>
</template>

<script>

export default {
name: ‘NavBarItem’,
data: function () {
return {
isOpen: false
}
},
computed: {

},
methods: {
ToggleState() {
this.isOpen = !this.isOpen;
this.$emit(“toggle-state”);
}
},
props: {
menu: {
type: Object,
default: function() {
return {
link: “#”,
title: “Main menu”,
active: true,
submenus: [
{
link: “#”,
title: “Submenu 1”,
},
{
link: “#”,
title: “Submenu 2”,
active: true
},
{
link: “#”,
title: “Submenu 3”,
},
]
}
}
}
}
}
</script>

<style scoped>

</style>

The goal is to click on one of the and show the menu contents while at the same time collapse the other components.

I thought about using an array of variables and bind it to the “show” prop and with an event listen to it and set every variable to false except the one form the component that sent the event.

How can I know wich component sent the event?

Any better idea on how to acomplish this task?

Solution :

I think, the best way to do it is to add a uniuque identifier property to each NavBarItem and a property for a selected NavBarItem. Then in the main component you can on click on NavBarItem set selected NavBarItem and in NavBarItem make the isOpen computed on the basis if current NavBarItem identifier equals the clicked NavBarItem. Something like this:

<template>
<aside class=”main-sidebar”>
<section class=”sidebar”>
<ul class=”sidebar-menu” data-widget=”tree”>
<nav-bar-user-profile-item></nav-bar-user-profile-item>
<nav-bar-item item-id=”1” :selected-item-id=”selectedNavbarItemId” @click=”selectedNavBarItemId = 1”></nav-bar-item>
<nav-bar-item item-id=”2” :selected-item-id=”selectedNavbarItemId” @click=”selectedNavBarItemId = 2”></nav-bar-item>
</ul>
</section>
</aside>
</template>

<script>
import NavBarUserProfileItem from ‘@/components/NavBar/NavBarUserProfileItem’;
import NavBarItem from ‘@/components/NavBar/NavBarItem’;

export default {
name: ‘NavBar’,
components: {
NavBarUserProfileItem,
NavBarItem
},
data: function(){
return {
selectedNavBarItemId: 0
}
},
methods: {
MenuHasBeenToggled(event) {
console.log(event);
}
}
}

And in NavBarItem

<template>
<li class=”treeview2 item” :class=”{‘menu-open’: isOpen, ‘active’: menu.active}” @click=”ToggleState”>
<a href=”#”>
<i class=”fa fa-th”></i>
<span>{ menu.title }</span>
<span class=”pull-right-container”>
<i class=”fa fa-angle-right pull-right”></i>
</span>
</a>
<collapse-transition>
<ul class=”treeview-menu” v-show=”isOpen”>
<li v-for=”submenu in menu.submenus” :key=”submenu.title” :class=”{‘active’: ((‘active’ in submenu) ? submenu.active : false)}”>
<b-link :href=”submenu.link”>
<i class=”fa fa-circle-thin”></i>
{ submenu.title }
</b-link>
</li>
</ul>
</collapse-transition>
</li>
</template>

<script>

export default {
name: ‘NavBarItem’,
data: function () {
return {

}
},
computed: {
isOpen:function(){
return itemId == selectedItemId;
}
},
methods: {

},
props: {
itemId:Number,
selectedItemId:Number,
menu: {
type: Object,
default: function() {
return {
link: “#”,
title: “Main menu”,
active: true,
submenus: [
{
link: “#”,
title: “Submenu 1”,
},
{
link: “#”,
title: “Submenu 2”,
active: true
},
{
link: “#”,
title: “Submenu 3”,
},
]
}
}
}
}
}
</script>

<style scoped>

</style>

[Vue.js] How do you pass an ID to a function that will use that ID to query data

So to start, this is my table which shows the students data:

<div class=”card-body table-responsive p-0”>
<table class=”table table-hover”>
<tr>
<th>Student ID</th>
<th>Name(Lastname, Firstname)</th>
<th>Contact</th>
<th>Modify</th>
</tr>
<tr v-for=”student in students.data” :key=”student.student_id”>
<td>{student.student_id}</td>
<td>{student.lastname | upFirstLetter}, {student.firstname | upFirstLetter} </td>
<td>{student.contact_no}</td>
<td>
<a href=”#” data-toggle=”modal” data-target=”#viewModal” @click=”loadStudentData(student.student_id)”>
<i class=”fas fa-eye text-teal”></i>
</a>
</td>
</tr>
</table>
</div>

When the view icon is clicked it calls and passes the student_id to a function named loadStudentData()

loadStudentData(id) {
this.form.show(‘api/loadData’ + id).then(({data}) => (this.studentsData = data));
}

and for the function show($id) inside the controller

public function show($id)
{
return Students::orderBy(‘student_id’, ‘asc’)
->join(‘student_details’, ‘student_details.student_id’, ‘students.student_id’)
->where(‘students.student_id’, ‘=’, $id)
->select(‘students.*‘, ‘student_details.*‘);
}

This is what I’ve tried so far and I cant seem to get it to work.
Thanks in advance.

Solution :

try Implicit Binding, that’s much more better

Solution 2:

I think you missed a slash on after ‘api/loadData’.It could be

loadStudentData(id) {
this.form.show(‘api/loadData/‘ + id).then(({data}) => (this.studentsData = data));
}

However, you did not publish the routes here.