Software

Setting v-bind:class with method not working

Vuejs - Wed, 2017-09-06 11:45

I am trying to set the style of a div with

<div v-for="q in questions" v-bind:class="{seen:isseen(q),unseen:isunseen(q)}">

The problem is that these functions get computed for each q, but I also need them to get recomputed when a different variable updates.

methods:{ isseen: function(id_1){ if(ans[id_1]==2) return true; else return false }, isunseen:function(id_1){ if(ans[id_1]!=2) return true; else return false; } }

Here, I need the

v-bind:class="{seen:isseen(q),unseen:isunseen(q)}"

computed even when ans[id_1] changes.

I have looked at the computed and watch approach, but cannot figure out what will work here.

Categories: Software

Laravel Mix (Vue + Stylus). Blank page on npm run watch

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

I start up a new Laravel + Vue + Stylus project, and i can't normally work because i always got blank page when adding/editing some styles on .styl files. And when i edit my .vue templates it come back to normal state.

My main.js file:

import Vue from 'vue'; import VueRouter from 'vue-router'; import { routes } from './routes/index'; import App from './App.vue'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes }); new Vue({ el: '#app', router, render: h => h(App) });

My webpack.mix.js file:

mix.js('resources/assets/js/main.js', 'public/js') .stylus('resources/assets/stylus/app.styl', 'public/css') .browserSync('localhost:8000');

Some strange thing that i noticed is that when i save my .styl file i got main.js like prod version(not compiled) and in console has an error:

Uncaught SyntaxError: Unexpected token import

If i save this file again i got normal compiled main.js file, but it doesn't render my App

And finally when i edit .vue templates all works perfect.

Categories: Software

Getting error " emitted value instead of an instance of error while compiling template " while implement vue table

Vuejs - Wed, 2017-09-06 11:21

I am trying to implement a Vue table by using Vue table plugin in my application using node module. Here I am getting an error while using all Vue table component. Here I install all Vue table plugin using npm and import them in my custom component.

My snippet of code is attached here with.

import Vuetable from 'vuetable/src/components/Vuetable.vue'; import VuetablePagination from 'vuetable/src/components/VuetablePagination.vue'; import VuetablePaginationDropdown from 'vuetable/src/components/VuetablePaginationDropdown.vue';

Here first I import the vue table plugin into my component. Then register such component into my custom component into vue instance.

data () { return{ columns: [ 'name', 'nickname', 'email', 'birthdate', 'gender', '__actions' ] } }, components : { Vuetable, VuetablePagination, VuetablePaginationDropdown }

And in template section i write this block of code.

<vuetable api-url="http://vuetable.ratiw.net/api/users" table-wrapper="#content" pagination-component="vuetable-pagination" :fields="columns"> </vuetable>
Categories: Software

Vue custom looping data with v-for

Vuejs - Wed, 2017-09-06 11:11

I have some data that I will loop using v-for. But I am a little confused when I want to display data using custom looping, like modulus.

The result I want is data shown every three items, will do grouping so have different class every 3 items.

The data I want :

<div class="col-md-4 hidecontent data_1" content="#data_0">1 Blablablabla</div> <div class="col-md-4 hidecontent data_1" content="#data_1">1 Blablablabla</div> <div class="col-md-4 hidecontent data_1" content="#data_2">1 Blablablabla</div> <div class="col-md-4 hidecontent data_2" content="#data_3">2 Blablablabla</div> <div class="col-md-4 hidecontent data_2" content="#data_4">2 Blablablabla</div> <div class="col-md-4 hidecontent data_2" content="#data_5">2 Blablablabla</div> <div class="col-md-4 hidecontent data_3" content="#data_6">3 Blablablabla</div> <div class="col-md-4 hidecontent data_3" content="#data_7">3 Blablablabla</div> <div class="col-md-4 hidecontent data_3" content="#data_8">3 Blablablabla</div>

You see, data_1 has 3 items. data_2 has 3 items and data_3 has 3 items

My Looping data :

<div class="col-md-4 hidecontent" v-for="(item, index) in this.$parent.items" :key="item._id" :content="['#data_' + index]"> <div class="features_item sm-m-top-30"> <div class="f_item_text"> <img v-bind:src="item.picture"> <span>{{ countTitle(item.title) }}</span> <p>{{ countSting(item.body) }}</p> </div> </div> </div>

I am confused when creating a modulus condition like :

if(i % 3 === 2)

How do I get every 3 recurrence data added to class names starting from data_1 and so on for the next 3 data

Categories: Software

Using datalist in Vue.js to console.log changed options data

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

I am working on an Vue application that allows you to choose from a list of companies. You can search for companies, select one from the list that comes up and then click a submit button that (for now) calls a function that console.logs the company you have chosen.

I have been using a select tag to display a list of companies and then console.log-ing what the users pick from this list. This works fine, but I would like to use datalist to to the same thing instead because it looks better with the search function I made.

However, when using datalist, the new data from the option that the user picked isn't shown in the console. It still displays the same companyId data that user was assigned when they logged in. It seems like the companyId data doesn't change in the same way as when using the select-tag.

Is there a way to make the datalist work in the same way as a select-tag, so that the data in companyId changes and is displayed in the console?

Here is my html template (with a datalist tag instead of select):

<template> <div class="select-company-search-box"> <label for="search-box">Company<br></label> <i class="fa fa-search" aria-hidden="true"></i> <input list="search-companies" id="search-box" type="text" v-model="search" placeholder="Type to search"></input> <datalist id="search-companies" v-if="filteredCompanies.length < 10" v-model="companyId"> <option v-for="company in filteredCompanies"> {{ company }} </option> </datalist></br> <button class="submit-button" @click="changeCompany()">Submit</button> </div> </template>

And here is my data and functions. The filteredCompanies() function filters through the company list and only displays relevant options, so that the entire list isn't displayed:

<script> export default { name: 'selectCompany', data() { return { companies: [], search: '', companyId: '', }; }, mounted() { reportService.general.getCompanies(this.editionId = store.getters['auth/user'].selectedEdition).then((response) => { this.companies = response; }); }, methods: { changeCompany() { changeCompany(companyId) { console.log(companyId); }, }, computed: { filteredCompanies() { return this.companies.filter(company => company.toLowerCase().match(this.search.toLowerCase())); }, }, }; </script>
Categories: Software

How to use vue.js component in laravel blade?

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

I registered component in my app.js like this:

Vue.component('navbar', require('./components/Navbar.vue'));

Now I want to import that component:

<template> <nav class="navbar">CODE HERE</nav> </template>

Into my blade.php file:

<body class=""> <div id="app"> <div class=""> <navbar></navbar> <-- here! @yield('content') </div> </div> </body>

What's the easiest way to do this?

Categories: Software

beforeRouteEnter infinite loop

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

I'm having this problem with Vue Router.

My scenario is to allow / to be loaded first, fetch some data from there and then it will go to /chat/:chatId route and render UI there, where :chatId param is set from the data I got from API.

I have / and ['chat', 'chat/:chatId'] as route alias.

I have in-component guard for this matter.

beforeRouteEnter(to, from, next) { store.dispatch('fetchOpenSessions') .then(() => { const firstChat = Object.keys(store.state.chatsidebar.openSessions)[0]; next({ name: 'chat', params: { chatId: firstChat } }); }); },

However this code ends up looping infinitely, causing the browser to hang.

My question is, how do I set chat/:chatId if my initial route is / or /chat without getting into infinite loop?

Categories: Software

Issue is update props with onchange(@change) in vue js 2

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

I am trying to update the data when doing on-change from the select box. Currently, i am able to the first time with the button click and also with on change. But I am not able to when doing the on-change multiple times.

<template> <div> <div class="row"> <select v-model="selectedemp" @change="filterempdata($event.target.value)"> <option value="">Select emp/option> <option v-for="option in empfilterlist" v-bind:value="option.value" v-bind:key="option.value">{{ option.text }}</option> </select> </div> <div class="row"> <empView v-if='loaded' :empDetails='empData'></empView> </div> <div class="col-lg-6 col-md-6"> <button type="button" id="btn2" class="btn btn-danger btn-md" v-on:click="getEmpDetails">Fetch Data</button> </div> </div> </template>

Javascript part:

data () { return { loaded: false, emptData: {}, empfilterlist: [ { text: 'Department', value: '1' }, { text: 'Status', value: '2' }, ], selectedemp: '', } }, methods: { filterempdata: function (selectedoption) { console.log('Onchange value - ' + selectedOption) Vue.set(this.empData, 'Department', selectedoption) }, getEmpDetails: function () { this.$http.get('http://localhost:7070/getemmdata') .then((response) => { this.empData = response.data this.loaded = true }, response => { console.log('test' + JSON.stringify(response)) } ) }

Child component javascript code:

export default { name: 'empView', props: ['empDetails'], data () { return { empid: this.empDetails.id, empname: this.empDetails.name } }, watch: { workflowDetails: function (changes) { console.log('data updated ' + JSON.stringify(changes)) this.empid = changes.id this.empname = changes.name this.department = changes.Department } } }
Categories: Software

How to send data using get without display parameters in url?

Vuejs - Wed, 2017-09-06 06:39

My case like this :

My view blade laravel like this :

{!! Form::open(['route' => 'shop.payment']) !!} <input type="hidden" name="result_type"> <input type="hidden" name="result_data""> ... <input type="radio" name="payment_method" value="transfer"> .... <checkout-view></checkout-view> {!! Form::close() !!}

In view blade laravel exist vue component of checkout view

The component like this :

<script> export default{ template:'<button @click="checkout" class="btn btn-danger pull-right" type="submit">Checkout</button>', methods: { checkout(e){ if(window.Laravel.hasOwnProperty('auth')) { $('#payment-form').attr('action', '/shop/payment/checkout') return true; } else { $('#payment-form').attr('action', '/shop/detail') $("#payment-form").attr('method', 'get') return true } } }, } </script>

My routes laravel like this :

Route::group(['prefix' => 'shop','as'=>'shop.'], function () { Route::get('detail', function(){ return view('shop.detail'); }); });

If no auth it will run else and the url like this :

http://myshop.dev/shop/detail?_token=FLFJ7MfWi1DZv88Uzk2lrBgVXLN6Y3WHTpskDIED&result_type=&result_data=&payment_method=transfer

I want remove the parameter, so the url like this :

http://myshop.dev/shop/detail

I try change to post

I change to be like this :

$('#payment-form').attr('action', '/shop/detail') $("#payment-form").attr('method', 'post') return true

And

Route::post('detail', function(){ return view('shop.detail'); });

But it does not work, there exist error :

POST http://myshop.dev/shop/detail 405 (Method Not Allowed)

What is the right solution to solve my problem?

Categories: Software

Async throwing SyntaxError: Unexpected token (

Vuejs - Wed, 2017-09-06 05:21

I'm running a test using the headless Chrome package Puppeteer:

const puppeteer = require('puppeteer') ;(async() => { const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto('https://google.com', {waitUntil: 'networkidle'}) // Type our query into the search bar await page.type('puppeteer') await page.click('input[type="submit"]') // Wait for the results to show up await page.waitForSelector('h3 a') // Extract the results from the page const links = await page.evaluate(() => { const anchors = Array.from(document.querySelectorAll('h3 a')) return anchors.map(anchor => anchor.textContent) }) console.log(links.join('\n')) browser.close() })()

And I'm running the script as: node --harmony test/e2e/puppeteer/index.js (v6.9.1)

But I get this error:

;(async() => { ^ SyntaxError: Unexpected token (

What could be the problem?

Note: I'm using Vue CLI's official Webpack template:

Categories: 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

Pages