Software

What does a SPA benefit embedded in an asp.net solution?

Vuejs - Wed, 2017-09-06 02:43

So I believe I understand the difference between SPAs and an ASP.NET MVC app as I have worked with both, but as I have seen a decent amount of tutorials embedding Angular, React, or Vue in ASP.NET or .NET Core apps, I am unclear as to why one would do this.

I'm not looking for right or wrong so much as what are some reason behind this architecture and is there any significant benefits?

Categories: Software

Vue js v-model diferents checkboxs

Vuejs - Wed, 2017-09-06 01:10

I'm a bit new with Vue Js. I'm trying to obtain the boolean value of each checkbox from a Vue component, but when I check one, the rest ones are checked as well, so I can check just one. I've try it with computed but no results. Does anyone can give any tip please

<v-card> <v-layout row wrap class="text-xs-center" v-for="ingredient in ingredients" :key="ingredient.id"> <v-layout column> <v-flex xs6> <v-checkbox color="light-blue lighten-2" v-bind:label="`${ingredient.name}`" v-model="checked" light></v-checkbox> </v-flex> </v-layout> <v-layout column> <v-flex xs6> <v-subheader>{{ingredient.price}} €</v-subheader> </v-flex> </v-layout> </v-layout> </v-card> export default { data: () => ({ checked: [], checked1: '', ingredients: [{ id: 1, name: "tomato", price: 2 }, { id: 2, name: "Cheese", price: 2.0 }, { id: 3, name: "Frankfurt", price: 2.25 }, { id: 4, name: "Mushrooms", price: 1.6 }, { id: 5, name: "Pepper", price: 2.5 }, { id: 1, name: "Ham", price: 2.75 }], }), computed: { checked() { return this.checked } } }
Categories: Software

Nuxt JS SSR title undefined

Vuejs - Wed, 2017-09-06 00:36

I'm using Nuxt JS/Vue to create an SEO friendly Server Side Rendered JS web app. Nuxt allows setting the head option in each Vue component which it then take and via vue-meta updates the page title. I get a user based on the route and then set the title to the user's name. This works when running a local server. But when I push this up to Firebase I get the title as undefined (on refresh).

Vue Component:

<template> <div class="user"> <h3>{{ name }}</h3> </div> </template> <script> import axios from 'axios' export default { data () { return { title: 'test' } }, head () { return { title: this.name, meta: [ { hid: 'description', name: 'description', content: 'My custom description' } ] } }, async asyncData ({ params, error }) { try { const { data } = await axios.get(`https://jsonplaceholder.typicode.com/users/${+params.id}`) return data } catch (e) { error({ message: 'User not found', statusCode: 404 }) } }, mounted () { console.log(this.name) this.title = this.name } } </script>
Categories: Software

Handling axios auth header dynamically within a custom api inside a vue.js

Vuejs - Tue, 2017-09-05 22:45

I'm having a bit of trouble with a api library I wrote.

So I have a vue.js app and in some of the components I've written I call a api library I've written.

Inside the api library I have some code like this:

import requests from 'axios'; var getApiToken = function() { const token = localStorage.getItem('token') if (token) { return token } return "" } // all requests need to have the api token inserted requests.defaults.headers.common['Access-token'] = getApiToken(); export default { apiRootUrl: "https://localhost:8080", buildUrl(endpoint) { return this.apiRootUrl + endpoint }, getInstanceList() { const endpoint = '/instances'; const url = this.buildUrl(endpoint) return requests.get(url) }, }

Now within my vue.js components I can do something like this

import ConfigApi from '../utils/ConfigApi.js'; export default { data: () => ({}), created() { ConfigApi.getConfig(this.instanceId, this.configId) .then(response => { // do something }); },

The issue I'm running into -
- api token expires - I trigger a login view that lets the user relogin - new token gets set in localstorage

[PROBLEM] the api library is already loaded and the header with the older token keeps being used. How can I have it "refresh" my api library or better dynamically get the token from localstorage on each requests?

Categories: Software

VueRouter + VueJs2 + MetisMenu = Collapse error

Vuejs - Tue, 2017-09-05 22:15

I'm new VueJs student, and i want to make a Menu and a Second level menu into this. I'm want to use Jquery-MetisMenu, so a downloaded it, put it on my Index.html and i made a router view to the Menu.

Here is my Menu.vue

<template> <div class="app"> <nav class="navbar-default navbar-static-side" role="navigation"> <div class="sidebar-collapse"> <ul class="nav metismenu" id="side-menu"> <li> <a href="#"><i class="fa fa-th-large"></i> <span class="nav-label"> Here First Level </span> <span class="fa arrow"></span></a> <ul class="nav nav-second-level collapse"> <li><a href="#"> Here Second Level </a></li> </ul> </li> </ul> </div> </nav> </div> </template>

Routes.js

import ContentTest from './ContentTest.vue' import Menu from './Menu.vue' const routes = [ //{path: '/login', component: LoginView }, { path: '/Menu', component: Menu, children: [ { path: '/Menu/ContentTest', component: ContentTest, name: 'ContentTest 1' }] }] export default routes

Body of Index.Html

<body> <!-- Main View --> <div id="container"> <div id="wrapper"> <router-view></router-view> </div> </div> <!-- Script Files --> <script src="dist/build.js"></script> <script src="./node_modules/jquery/dist/jquery.min.js"></script> <script src="./node_modules/metismenu/dist/metisMenu.min.js"></script> </body>

The problem is with the collapse, when i click on "Here First Level", the URL changes to "#" and it get lost. I tried to put nothing inside href, but didn't work.

Waiting answers! Thanks a lot!!

Categories: Software

VUEX Two data binding in v-for using mutations instead of manipulating directly

Vuejs - Tue, 2017-09-05 22:00

I need some help and I haven't found anything on the forums related to this question. I have a big deep nested object and my question is how to bind checkboxes and radio in a v-for loop using mutations instead of changing the state directly. I've foun that you can use a :value with an event, and that may works but anyway...how could I bind and get access to the specific object. I just can't figure it out how could I match'em both, the checkbox with the current parent in the loop.

JSON Object response (just part of the main structure)

{ "inspectionSheetForm": { "inspectionAreas": [{ "inspectionAreaName": "Category name", "inspectionParts": [{ "name": "Part name", "partSubcategories": [{ "name": "Partsubcategory name", "checkGood": false, "checkSuggested": false, "checkRequired": false, "checkNotInspected": false, }] }] }] } }

Parent component:

<template v-for="(inspectionArea, step) in inspectionAreas"> <inspection-parts :inspectionArea="inspectionArea"></inspection-parts> </template>

Child

The child receives the prop 'inspectionArea' and the 'getParts' array is a computed property:

<template v-for="part in getParts[0]"> <template v-for="subs in part.partSubcategories"> <input type="checkbox" v-model="subs.checkGood"> <input type="checkbox" v-model="subs.checkSuggested"> <input type="checkbox" v-model="subs.checkRequired"> <input type="checkbox" v-model="subs.checkNotInpespected"> </template> <script> computed: { getParts () { return this.$store.getters.getInspectionParts(this.inspectionArea.inspectionAreaName) } } </script>

Getter:

getInspectionParts: state => inspectionAreaName => { return state.inspectionSheet.inspectionSheetForm.inspectionAreas.filter(cat => { return cat.inspectionAreaName === inspectionAreaName }).map(part => { return ((part.inspectionParts.length === 0) ? part.inspectionTires : part.inspectionParts) }) }
Categories: Software

issue caused the Row selection overwrite

Vuejs - Tue, 2017-09-05 20:07

I asked question on adding/removing row in how to use "v-for" for adding or removing a row with multiple components

However, I got a bug: when I adding a row, the items in the first row filled to second row and when I changed the second row, the 1st row is also overwritten as the same as 2nd row.

i must did sth really wrong.

in .js

var data1={selected: null, items: ["A1","B1"]}; Vue.component('comp1',{ template: ` <select v-model="selected"> <option disabled value="">Please select</option> <option v-for="item in items" :value="item">{{item}} </option> </select>`, data:function(){ return data1 } }); var data2={selected: null, items: ["A2","B2"]}; Vue.component('comp2',{ template: ` <select v-model="selected"> <option disabled value="">Please select</option> <option v-for="item in items" :value="item">{{item}} </option> </select>`, data:function(){ return data2 } }); new Vue({ el: '#app', data: { rows: [] }, computed:{ newId(){ return this.rows.length == 0 ? 1 : Math.max(...this.rows.map(r => r.id)) + 1 } }, methods: { addRow: function() { this.rows.push({id: this.newId }); }, removeRow: function(row) { this.rows.splice(this.rows.indexOf(row), 1) } }, });

in .html

<div id="app"> <div v-for="row in rows"> <comp1></comp1> <comp2></comp2> <button @click="removeRow(row)">Remove Row</button> </div> <button @click="addRow">Add Row</button> </div>
Categories: Software

Transition with partial opacity

Vuejs - Tue, 2017-09-05 19:39

I'm following the guide here https://vuejs.org/v2/guide/transitions.html to animate a popup and their overlay. I need the overlay with a final opacity of 0.5 but Vue set it to 1 at the end. I tried something like this, but Vue animate the opacity to 0.5 and abruptly change it to 1 at the end of the animation:

.fade-enter { opacity: 0; } .fade-enter-active { transition: opacity 2s; } .fade-enter-to { opacity: 0.5; }

Here is a test that illustrate the problem https://jsfiddle.net/50wL7mdz/58865/

Categories: Software

How to bind null value in anchor tag and null element in v-for in Vuejs

Vuejs - Tue, 2017-09-05 18:53

I'm having a table something like this:

Data table

I'm facing two difficulties here:

  1. I'm having a document link, which in create form is not mandatory field, so the data which comes through response sometimes have null value which throws error and makes table data disappear. I'm trying to implement something like this

    <td class="text-center"> <a :href="item.document.link" target="_blank"> <i class="fa fa-eye text-navy"></i> </a> </td>

This throws error:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'link' of null"

  1. I'm having two columns for target price old and revised, during the creation of the data set only one target price is being inserted and the response which sends the data is inside one variable something like this:

    "target_prices": [ {"id":3,"research_id":16,"price":"90"} {"id":4,"research_id":16,"price":"91"} ]

So in this case there might be only one data inside target_price as:

"target_prices": [ {"id":3,"research_id":16,"price":"90"} ]

this makes table shift as, you can see in the image the table is being shifted, I'm using a simple v-for loop to show the values.

<td class="text-center" v-for="target in item.target_prices">{{ target.price }}</td>

I simply want to display null or NA under Old if only one value is available. and show the difference of both under change in TP Help me out in this. Thanks.

Categories: Software

Problems with CORS using vue

Vuejs - Tue, 2017-09-05 17:31

We are using the vue-bulma-admin scaffold on a project, which already uses webpack, and we can't seem to perform any POST/PUT requests to our API (which already sets access-cross-allow-origin headers to *), only GET requests works. From different front-ends that consumes our API, we don't have this problem, only with this specific front-end, which gives as this common error:

"No 'Access-Control-Allow-Origin' header is present on the requested resource."

We already tried to set custom headers on axios/vue-resource, but with no success. As I said, using the same routes through Postman / different front-ends or with the CORS chrome extension, everything works fine.

Any ideas to work around this?

Categories: Software

"document is not defined" in Nuxt.js

Vuejs - Tue, 2017-09-05 17:24

I am trying to use Choices.js within a Vue component. The component compiles successfully, but then an error is triggered:

[vue-router] Failed to resolve async component default: ReferenceError: document is not defined

In the browser I see:

ReferenceError document is not defined

I think this has something to do with the SSR in Nuxt.js? I only need Choices.js to run on the client, because it's a client only aspect I guess.

nuxt.config.js

build: { vendor: ['choices.js'] }

AppCountrySelect.vue

<script> import Choices from 'choices.js' export default { name: 'CountrySelect', created () { console.log(this.$refs, Choices) const choices = new Choices(this.$refs.select) console.log(choices) } } </script>

In classic Vue, this would work fine, so I'm very much still getting to grips with how I can get Nuxt.js to work this way.

Any ideas at all where I'm going wrong?

Thanks.

Categories: Software

Working With Data in Both A Computed Property and a Life Cycle Hook

Vuejs - Tue, 2017-09-05 17:05

I am fairly new to VueJS and I just want to make sure that the following code is written properly (and that there is not a better way to do this).

Here is the code:

<template> <section class="hero" :style="bgSrc"> <slot></slot> </section> </template> <script> export default { props: [ 'src', 'srcXs', 'srcSm', 'srcMd', 'srcLg', 'srcXl' ], data () { return { xs: 0, sm: 600, md: 1024, lg: 1440 - 16, xl: 1920 - 16, sourceImage: '', screenWidth: '' } }, computed: { bgSrc () { if (this.src) { return { backgroundImage: 'url(' + this.sourceImage + ')' } } } }, mounted () { let screenWidth = document.documentElement.clientWidth if (screenWidth >= this.xs && screenWidth < this.sm) { this.sourceImage = this.srcXs } if (screenWidth >= this.s && screenWidth < this.md) { this.sourceImage = this.srcSm } if (screenWidth >= this.md && screenWidth < this.lg) { this.sourceImage = this.srcMd } if (screenWidth >= this.lg && screenWidth < this.xl) { this.sourceImage = this.srcLg } if (screenWidth >= this.xl) { this.sourceImage = this.srcXl } } } </script>

The goal is to create a background image for a hero section, but allow for different sized images for different screen sizes.

Here is how an implementation would look:

<template> <hero-section class="full secondary" src="http://via.placeholder.com/480x270" src-xs="http://via.placeholder.com/480x270" src-sm="http://via.placeholder.com/720x405" src-md="http://via.placeholder.com/1440x810" src-lg="http://via.placeholder.com/1920x1080" src-xl="http://via.placeholder.com/2560x1440" > <v-container fill-height> <v-layout column align-center justify-center> <!-- TEXT GOES HERE --> </v-container> </hero-section> </template>

Am I doing this right, or is there a better way to do it?

Thanks.

Categories: Software

Vue + Typescript: Passing Property once got data from server

Vuejs - Tue, 2017-09-05 16:50

I'm trying to pass an object as a property once I get it back from the server but I get this error:

Property or method "section" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Error in render function: "TypeError: Cannot read property 'name' of undefined"

Here is my form.ts:

import Vue from 'vue'; import { Component } from 'vue-property-decorator'; import { Form } from '../../models/models'; @Component({ components: { SectionComponent: require('../section/section.vue') } }) export default class FormComponent extends Vue { form: Form = <Form>{}; mounted() { fetch('forms/new-instance/2') .then(response => response.json() as Promise<Form>) .then(data => { this.form = data; }); } }

form.vue:

<template> <section class="section"> <h2 class="title">{{form.formName}}</h2> <b-tabs type="is-boxed" position="is-centered"> <b-tab-item v-for="page in form.pages" :label="page.name" :key="page.id"> <section-component v-for="section in page.sections" :key="section.id" :section="section"> </section-component> </b-tab-item> </b-tabs> </section> </template> <script src="./form.ts"></script>

section.ts:

import Vue from 'vue'; import { Component, Prop, Watch } from 'vue-property-decorator'; import { Section } from '../../models/models'; @Component({ components: { QuestionComponent: require('../question/question.vue') } }) export default class SectionComponent extends Vue { @Prop() section: Section; }

section.vue:

<template> <div class="box"> <legend class="subtitle">{{section.name}}</legend> </div> </template> <script src="./section.ts"></script>

Finally, my interfaces:

export interface Section { id: number; name: string; } export interface Page { id: number; name: string; order: number; formId: number; sections: Section[]; } export interface Form { formName: string; formId: number; pages: Page[]; }

I believe the issue is to do with my <section-component></section-component> but I'm not sure where I am going wrong? Any help would be appreciated, thanks.

Categories: Software

vuejs: Component for <tr>, how to implement?

Vuejs - Tue, 2017-09-05 15:45

After reading docs & forums for hours... still have no answer.

Have the following JS/HTML:

Vue.component("my-component", { props: ["id"], render: function(h) { return h("tr", this.$slots.default); } }); var vapp = new Vue(); <script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script> <table> <tr is="my-component" :name="yo"> <td> <span v-text="name"></span> </td> </tr> </table>

Use tr + "is" attribute to specify component within the table otherwise browser will hoist it out as invalid content. Done

Use render + h("tr"...) because vuejs doesn't render tr element, but instead table > td and again browser hoist it out.Done

Now I have table > tr > td rendered well but how can I add children bound to the props/data, so I will see "yo" on the screen.

Thanks a lot!

Categories: Software

Why is my bulma modal not displaying when data is set to true? (Vue.js)

Vuejs - Tue, 2017-09-05 15:45

New to Vue.js and bulma. I am trying to get a modal pop up to work, so far I have this from including the modal component in the main App.vue file:

<template lang="pug"> div#app navigation-menu menu-modal transition(name="fade") router-view </template>

enter image description here

I only want the modal to show if the data is set to true here (still in App.vue, inside the script tags):

export default { name: 'app', components: { NavigationMenu, MenuModal }, data: { showModal: true } }

I tried adding this inside the template tags (Vue.js):

enter image description here

But the modal just disappeared from the page, even when showModal is set to true in data.

Any idea how to make the modal appear when data is set to true and disappear when set to false?

Categories: Software

How to use vuejs module on object

Vuejs - Tue, 2017-09-05 15:16

I have the following piece of code:

<div id="app"> <input type="text" name="" v-model="user.phones"> </div> <script> new Vue({ el: '#app', data() { return { user: { phones: [] } } } }); </script>

Whenever user writes a phone, I want that to be injected in the user.phones model. But since the phones model is an array, the number is not being assigned to user.phones

Categories: Software

Pass variable from route to blade view

Vuejs - Tue, 2017-09-05 14:56

I have app in Laravel and Vue.js. In navbar.blade.php I did something like this:

<p>{!! $test !!}</p>

Now I want to change that variable to text using only routing. Can I do it? How?

If not, how I can keep that variable but change it in vue.js?

Categories: Software

How to implement flowtype in Nuxt.js

Vuejs - Tue, 2017-09-05 14:19

I am currently trying to convert our existing vue.js project into nuxt.js. I am unable to add flowtype support in nuxt.js. when i run the flow server it says no errors!! but running npm run dev, its throwing error on the flow syntax.

.flowconfig [include] pages/**/.* components/**/.* layouts/**/.* apiRoutes/.* store/.* utils/.* [ignore] .*/build/.* .*/config/.* .*/dist/.* .*/node_modules/.* .*/static/.* .*/test/.* .*/ssl/.* .*/.nuxt/.* [libs] ./flow/ [options] emoji=true module.file_ext=.vue module.file_ext=.js server.max_workers=3 log.file=./flow.log suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe unsafe.enable_getters_and_setters=true module.system.node.resolve_dirname=node_modules module.name_mapper='^.*\.css$' -> 'empty/object' module.name_mapper='^.*\.js$' -> 'empty/object' module.name_mapper='^@/\(.*\)$' -> '<PROJECT_ROOT>/\1'

i've added all the neccessary babel and eslint packages.

.babelrc { "presets": [ ["env", { "modules": false }], "stage-2", ["es2015", {"modules": false }], "flow-vue" ], "plugins": [ "transform-runtime", "transform-class-properties", "syntax-flow", "transform-flow-strip-types" ], "comments": false, "env": { "test": { "presets": ["env", "stage-2"], "plugins": [ "istanbul" ] } } } .eslintrc.js module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true, node: true, jquery: true }, extends: [ 'standard', 'plugin:flowtype/recommended' // 'plugin:vue/recommended' ], // required to lint *.vue files plugins: [ 'html', 'flowtype-errors', 'flowtype' ], // add your custom rules here rules: { 'flowtype-errors/show-errors': 2, // allow paren-less arrow functions 'arrow-parens': 0, 'semi': ["error", "always"], // allow async-await 'generator-star-spacing': 0 }, globals: {} }

On running npm run dev, it doesnt parse flowtype syntax

flowtype_error

Categories: Software

Switcher of languages on Vue.js

Vuejs - Tue, 2017-09-05 13:06

Good day :)

Got to study Vue.js 2nd version, everything is still going according to plan, but there are some nuances and I would like to hear a pro

Now we turn to the essence of the problem

On the site there is a language switch, it works all by standards, in the template comes arrays of languages:

$headerBar = [ 'langs' => [ [ 'name' => 'Українська', 'img' => 'images/flags/ua.png', 'code' => 'ua', 'active' => true, ], [ 'name' => 'Русский', 'img' => 'images/flags/ru.png', 'code' => 'ru', 'active' => false, ], [ 'name' => 'English', 'img' => 'images/flags/uk.png', 'code' => 'uk', 'active' => false, ] ] ];

Language output template:

<template slot="language-bar"> <language-switcher v-bind:langs='{!! json_encode($langs) !!}'></language-switcher> </template>

And the component vue.js itself:

<template> <div class="lang-currency-switcher-wrap" :class="{ show: isVisible }"> <div class="lang-currency-switcher dropdown-toggle" @click="isVisible = true"> <span class="language"> <img :alt="activeLang.name" :src="activeLang.img"></span> <span class="currency">{{ activeLang.code }}</span> </div> <div class="dropdown-menu"> <a v-for="lang in langs" v-if="!lang.active" class="dropdown-item"> <img :src="lang.img" alt="">{{ lang.name }} </a> </div> </div> </div> </template> <script> export default { props: ['langs'], data() { return { isVisible: false }; }, computed: { activeLang() { let activeLang = []; for (let lang of this.langs) { if (lang.active) { activeLang = lang; } } return activeLang; } }, mounted() { } } </script>

It works like this: The server renders an array of languages ​​with clever calculations, one of which is active, it all comes to the blade template and the vue.js component is already called

The component vue.js in its turn outputs an available list of languages ​​except active, and the active calculates and displays for the user.

When the user clicks on the language wrapper, then vue displays the entire available list.

Now the question is:

How correctly to hide all languages, in that cases, if the user clicked on any of the areas of the site, except the most wrapper languages?

Also interesting is the criticism, perhaps it could have been done differently, in a more beautiful way :)

Thank you.

Categories: Software

What is best way indicate best value in table Vue

Vuejs - Tue, 2017-09-05 12:48

Hello i have table in Vue template and in table have speed's and time's values. And i want indicate the higher speed and lower time value. And i can have several equal values.

I call method set do something calculation (its just example, sorry for this horror) with array and object bestOf and in template show with conditional directive.

Q:How correctly i can show this best values in tables with Vue API (directives, computed values) or maybe not need use Vue API (i did so)?

Code:

var table = new Vue({ el: '#app-4', template: ` <div v-if="visible" id="sumTable"> <table id="dataTable"> <tbody> <tr v-for="(competitor,index) in competitors"> <td>{{competitor.start}}<span style="color:red" v-if="bestOf.start[index]">&#9733</span></td> <td>{{competitor.speed}}<span style="color:red" v-if="bestOf.speed[index]">&#9733</span></td> </tr> </tbody> </table></div>`, data: { visible: false, competitors: [{ start: '', speed: '', }], bestOf: { start: {}, speed: {}, } }, created: function () { window.addEventListener('keyup', this.tableVisible) }, methods: { tableVisible: function (event) { if (event.keyCode === 88) { this.visible = !this.visible; if (this.visible) { window.calculateRaceStatsTable() } } }, set: function (newArray) { newArray.data.forEach(function(competitor,index,array){ if (!this.bestOf['start'].value || this.bestOf['start'].value > parseFloat(competitor['start'])){ this.bestOf['start'] = {}; Vue.set(this.bestOf['start'],'value',parseFloat(competitor['start'])) Vue.set(this.bestOf['start'],index,true) } else if (this.bestOf['start'].value === parseFloat(competitor['start'])) { Vue.set(this.bestOf['start'],index,true) } if (!this.bestOf['speed'].value || this.bestOf['speed'].value < parseFloat(competitor['speed'])){ this.bestOf['speed'] = {}; Vue.set(this.bestOf['speed'],'value',parseFloat(competitor['speed'])) Vue.set(this.bestOf['speed'],index,true) } else if (this.bestOf['speed'].value === parseFloat(competitor['speed'])) { Vue.set(this.bestOf['speed'],index,true) } }.bind(this)) this.competitors = newArray.data.slice() } } })
Categories: Software

Pages