Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

Error while installing vue-cli

Sun, 2017-09-10 08:28

When i run npm install -g vue-cli , it continuously throws this error message:

Screen shot

npm ERR! path C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json npm ERR! code EPERM npm ERR! errno -4048 npm ERR! syscall unlink npm ERR! Error: EPERM: operation not permitted, unlink 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' npm ERR! at Error (native) npm ERR! { Error: EPERM: operation not permitted, unlink 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' npm ERR! at Error (native) npm ERR! stack: 'Error: EPERM: operation not permitted, unlink \'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json\'\n at Error (native)', npm ERR! errno: -4048, npm ERR! code: 'EPERM', npm ERR! syscall: 'unlink', npm ERR! path: 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' } npm ERR! npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\End User\AppData\Roaming\npm-cache_logs\2017-09-10T06_15_03_457Z-debug.log

  • I tried all the possible solutions found online :

    • running from windows cmd with administrator access,

    • npm cache clean

    • closed my text editor

    • restarted my PC

Please do help me solve this issue.

Categories: Software

CSS/JS to imitate multiple mobile app screens: left-to-right orientation, one-at-a-time behavior

Sun, 2017-09-10 06:59

I am working on a Flask / Vue.js web app that I want to have work well with both laptop and mobile browsers. The layout I've chosen is to have a series of mobile-screen-shaped areas that are oriented in a left-to-right fashion when viewed on a laptop browser. Currently when viewed on mobile those mobile-screen-sized areas get shifted into a top-to-bottom orientation, and the user can scroll the screen up and down to go through them all.

What I'd like to do is to have the mobile CSS instead simulate a mobile app by having those cards(?) oriented left-to-right (like the laptop view), and have a swipe shift each one into view or out of view, but always snapping to a single card at a time, rather than displaying 1/4th of the first card and 3/4ths of the second card (for example).

Current laptop browser view: enter image description here

Desired mobile behavior: enter image description here

Categories: Software

Custom event in Vuejs2

Sun, 2017-09-10 04:02

I'm not understanding the Custom Event in Vuejs2.

I have a component named as user-navbar witch contains a dropdown menu, when change I execute this method:

handleCurrentServerChange: function(name, zoneid, currency_name) { /* Code omitted */ this.$emit('server-changed', { serverznid: zoneid }); },

Wich emit an event called server-changed and I want to listen to this event in another component accounts-linked.

<accounts-linked inline-template :server_data="server_data" @server-changed="handleServer">

When the event is emitted I should call the method handleServer. But isn't working. This is the method:

handleNewMessage: function(value) { alert(value); }

I got few errors

[Vue warn]: Property or method "handleServer" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. [Vue warn]: Invalid handler for event "server-changed": got undefined

What am I doing wrong?

Categories: Software

Search Bar Filter Using Vue with child component

Sun, 2017-09-10 02:05

I am creating a dynamic search bar that will filter a sidebar full of names based on user input. However, I am having trouble temporarily hiding and showing data based on the search bar's value on keyup. What is the best way to achieve this the "Vue way"?

On keyup, I want to filter through all of the this.people data and only show names that contain the value of the search input.

Below is what my code looks like

//Javascript Vue.component('sidebar',{ props: ['people', 'tables'], data: () => { return { fullName: '' } }, computed: { computed() { return [this.people, this.tables].join() } }, template: ` <div id="sidebarContain" v-if="this.people"> <input id="sidebar-search" type="text" placeholder="Search..." @keydown="searchQuery"> <select id="sidebar-select" @change="sidebarChanged"> <option value="AZ">A-Z</option> <option value="ZA">Z-A</option> <option value="notAtTable">No Table</option> <option value="Dean's Guest">Dean's Guest</option> <option value="BOO | VIP">BOO | VIP</option> </select> <div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)"> <span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span> <span v-else>{{person.first_name + ' ' + person.last_name}}</span> </div> </div> `, methods: { isCheckedIn(person) { return person.reg_scan == null ? true : false; }, isHidden(person) { console.log("here"); }, calcRegColor(person) { switch(person.registration_type) { case "Dean's Guest" : return { color: 'purple' } break; case "BOO | VIP" : return { color: 'brown' } break; case "Student" : return { color: 'green' } break; case "Faculty": case "Staff": return { color: 'blue' } break; case "Alumni Club Leader": return { color: 'gold' } break; case "Table Guest" : return { color: 'pink' } break; default: return { color: 'black' } } } }, watch: { computed() { console.log("People and Tables Available"); } } }); //HTML <div id="app"> <sidebar :people="people" :tables="tables"></sidebar> </div>
Categories: Software

What does attribute "for" a label does (Vue.js)

Sat, 2017-09-09 22:56

I am playing around with this simple example trying to understand what attribute "for" does and can't seem to figure it out. I tried changing the value of "for" attribute and even removing it completely and it still works just fine (at least on the appearance). I would appreciate if someone can give me an explanation.

I just started to study Vue.js so this might be a very simple answer.
Categories: Software

Best practice to make multiple Vuejs javascript files work together

Sat, 2017-09-09 22:24

I can't find much information on the web with explanation on how to use multiple vuejs instances and make them work together.

Please, can someone show me his code style on how to do that?

I have a main /resources/assets/js/app.js:

Vue.component('google-maps', require('./components/Gmaps.vue')); export const App = window.App = new Vue({ el: '#app', mounted(){ // Listen for an event socket.on('alarm-channel:App\\Events\\AlarmCreated', ({data}) => { return this.alarmCreated(data.alarm); }); }, data: { users: [], alarms: [] // #01 - should be in Alarms.js }, methods: { /* Newly registered alarm */ alarmCreated(alarm){ this.alarms.push(alarm); // #01 - should be in Alarms.js } } });

How can I call a same new Vue() inside /resources/assets/js/alarms.js to make it work together ?:

Categories: Software

Rails data confirm with vue.js

Sat, 2017-09-09 21:25

I am trying to do away with jQuery in my Rails 5.1 app and move to use only Vue.js.

I have three questions in this regard:

  1. Is this a sensible thing to do? Can Vue.js fully replace jQuery or should they co-exist?
  2. How would I replace all the data-confirm niceties that Rails provides by default and convert them to their Vue equivalent?
  3. How would I localize strings such as the data-confirm strings?

Just trying to get an idea of whether this is feasible. Thanks!

Categories: Software

How to use Visual Studio 2017 and Vue single file components

Sat, 2017-09-09 21:08

I use Visual Studio 2017 and have a fair amount of ASPNET Core invested. That being said, I do like using Vue.js 2.0 for some UI workflow stuff on certain pages. I can't seem to find a suitable, and lightweight, way to compile a .vue file (single file component) and end up with a clean output .js and .css file. I've used npm, vue-cli, and webpack, but the resulting .js file for my single file component contains a bunch of other SPA, export, etc. overhead.

Isn't there just an easy way to use VS such that when a .vue file was saved, it would auto-generate the .js and .css file (I use LESS css) cleanly?

I guess the main reason I want to use a .vue file is to get syntax highlighting on the HTML as well as having my all in a common location.

Any thoughts? I would hope you could have configured VS to do a vue-cli (or some other tool) compile upon save like it does with .less files for css, and create a new .js and .css file. Something tells me webpack could do this with a custom config, but no one appears able to articulate exactly how to do this in detail.

Categories: Software

How to attach events in vue directives?

Sat, 2017-09-09 21:05

I need to attach functions to element using directives. I want to do it with Vue method $on, but it's not working. When I do it with addEventListener, event.target.value gives me unchanged value after first input, second works correctly. How to fix it?

Example: jsfiddle.net rjeu8Lc1/1/

Categories: Software

Vuejs routing working only partially.

Sat, 2017-09-09 20:34

My App works just fine, if I put routes without childrens (nesting) but I tried to nest it just now and converted my routes to this: in routes.js

import alphabetsPage from './components/views/pages/alphabets.vue' import dictionaryPage from './components/views/pages/dictionary.vue' import numbersPage from './components/views/pages/numbers.vue' import LayoutView from './components/views/Layout.vue' const routes = [{ path: '/', name: 'Home', component: LayoutView, children: [{ path: 'basic', name: 'Basic', component: alphabetsPage, children: [{ path: 'alphabets', name: 'Aphabets', component: alphabetsPage }, { path: 'numbers', name: 'Numbers', component: numbersPage }] }] }] export default routes

If I go to / or click on route <router-link to="/basic/alphabets" tag="li"><a>numbers</a></router-link> I can see the alphabetsPage component, however if I go click on <router-link to="/basic/numbers" tag="li"><a>numbers</a></router-link> the route doesn't work. I have a numbersPage componet working.

This must be from the routes, because, if I don't use children and just define the path in routes as /basic/numbers or /basic/alphabets it works.

Categories: Software

Vue js interpolation values sum

Sat, 2017-09-09 20:29

There exist any way in Vue js to make a sum between two interpolation values inside an html tag?

ex:

value1= 5 value2= 3

<span> {{value1}} + {{value2}}</span>

So I would like to know if its posible to obtain a third value rendered on the span tag adding the two values.

Categories: Software

Vue.js (2.0) unit test issue

Sat, 2017-09-09 18:45

I am trying to perform unit test on vuex actions, using Mocha and Sinon

here is my action.spec.js

import actions from '@/vuex/actions' import * as types from '@/vuex/mutation_types' describe('actions.js', () => { var server, store, lists, successPut, successPost, successDelete successDelete = {'delete': true} successPost = {'post': true} successPut = {'put': true} beforeEach(() => { // mock shopping lists lists = [{ id: '1', title: 'Groceries' }, { id: '2', title: 'Clothes' }] // mock store commit and dispatch methods store = { commit: (method, data) => {}, dispatch: () => { return Promise.resolve() }, state: { shoppinglists: lists } } sinon.stub(store, 'commit') // mock server server = sinon.fakeServer.create() server.respondWith('GET', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(lists)) }) server.respondWith('POST', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPost)) }) server.respondWith('PUT', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPut)) }) server.respondWith('DELETE', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successDelete)) }) server.autoRespond = true }) afterEach(() => { // restore stubs and server mock store.commit.restore() server.restore() }) describe('populateShoppingLists', () => { it('should call commit method with POPULATE_SHOPPING_LIST string parameter', done => { actions.populateShoppingLists(store).then(() => { expect(store.commit).to.have.been.calledWith(types.POPULATE_SHOPPING_LISTS, lists) done() }).catch(done) }) }) describe('changeTitle', () => { it('should call commit method with CHANGE_TITLE string', (done) => { let title = 'new title' actions.changeTitle(store, {title: title, id: '1'}).then(() => { expect(store.commit).to.have.been.calledWith(types.CHANGE_TITLE, {title: title, id: '1'}) done() }).catch(done) }) }) describe('updateList', () => { it('should return successful PUT response', (done) => { actions.updateList(store, '1').then((data) => { expect(data.data).to.eql(successPut) done() }).catch(done) }) }) describe('createShoppingList', () => { it('should return successful POST response', (done) => { let newList = { title: 'new list', id: '3' } actions.createShoppingList(store, newList).then((testResponse) => { console.log('testResponse: ', testResponse) expect(testResponse.body).to.eql(successPost) done() }).catch(done) }) }) })

here is my action.js

import { CHANGE_TITLE, POPULATE_SHOPPING_LISTS } from './mutation_types' import api from '../api' import getters from './getters' export default { populateShoppingLists: ({ commit }) => { return api.fetchShoppingLists().then(response => { commit(POPULATE_SHOPPING_LISTS, response.data) }) }, changeTitle: (store, data) => { store.commit(CHANGE_TITLE, data) return store.dispatch('updateList', data.id) }, updateList: (store, id) => { let shoppingList = getters.getListById(store.state, id) return api.updateShoppingList(shoppingList) }, createShoppingList: (store, shoppinglist) => { return api.addNewShoppingList(shoppinglist).then((actionResponse) => { console.log('actionResponse: ', actionResponse) store.dispatch('populateShoppingLists') }) }, }

running my unit tests , I have an issue with the createShoppingList test

console.log

actions.js populateShoppingLists ✓ should call commit method with POPULATE_SHOPPING_LIST string parameter changeTitle ✓ should call commit method with CHANGE_TITLE string updateList ✓ should return successful PUT response LOG LOG: 'actionResponse: ', Response{url: 'http://localhost:3000/shoppinglists', ok: true, status: 200, statusText: 'OK', headers: Headers{map: Object{Content-Type: ...}}, body: Object{post: true}, bodyText: '{"post":true}'} LOG LOG: 'testResponse: ', undefined createShoppingList ✗ should return successful POST response undefined is not an object (evaluating 'testResponse.body') webpack:///test/unit/specs/vuex/actions.spec.js:90:28 <- index.js:15508:28 webpack:///~/vue-resource/dist/vue-resource.es2015.js:151:0 <- index.js:17984:52 webpack:///~/vue/dist/vue.esm.js:701:0 <- index.js:3198:18 nextTickHandler@webpack:///~/vue/dist/vue.esm.js:648:0 <- index.js:3145:16

whicj indicates that in the createShoppingList action, the reponse is not sent back on the return, so expect(testResponse.body).to.eql(successPost) is not true...

what's wrong with my Promise handling in this case ?

thanks for feedback

Categories: Software

Vue js dynamic data component

Sat, 2017-09-09 18:19

I'm passing some dynamic data from a parent component to a child component using props . I'm displaying the child component and the script. So I would like to know how I can add myColor prop to total value and show it an render the result in a final value. I'm using Vue 2 and webpack.

<v-layout> <v-layout> <v-flex > <h3 >Total price:</h3> </v-flex> </v-layout> <v-layout> <v-flex <v-subheader> {{total}} {{myColor}} €</v-subheader> </v-flex> </v-layout> </v-layout> <script> export default { props: ['myColor'], data: () => ({ checked1: '', showCart: false, colors: [{ id: 1, name: "white", price: 2, checked: '', }, { id: 2, name: "black", price: 2.0, checked: '', }, { id: 3, name: "Grey", price: 2.25, checked: '', }, { id: 4, name: "Blue", price: 1.6, checked: '', }, { id: 5, name: "Red", price: 2.5, checked: '', }, { id: 6, name: "Yellow", price: 2.75, checked: '', }], }), computed: { total: function() { var total = 0; for (var i = 0; i < this.colors.length; i++) { if (this.colors[i].checked) { total += this.colors[i].price; } } return total; }, }, } </script>
Categories: Software

How can I trigger a method within a v-if tag (without v-on)?

Sat, 2017-09-09 17:37

I have a template tag with a v-if condition. I want to trigger a method when this condition is true. Something like:

<template v-if="condition"> {{ doit() }} //trigger method </template>

I want to call the doit method when condition is true. How can I do that?

Categories: Software

Vue.js - setting up the basics for a multi-step form

Sat, 2017-09-09 17:12

I'm trying to make a simple multi-step form for my Rails 5 app using Vue.js. It's my first time using Vue so I am a bit stuck on how to make things work properly.

Right now I am trying to do the following:

  1. Click a Next button and set the li elements from step 1 to step N to have a class active.
  2. Click a Previous button and remove class active from step N.

Quite simple. Here's what I've got so far but I don't know where to go from here:

import Vue from 'vue/dist/vue.esm' document.addEventListener('DOMContentLoaded', () => { Vue.component('step-item', { props: ['step'], template: '<li :class="{active: isActive}">{{ step.text }}</li>', data: function() { return { isActive: true // Right now I set them all to true } } }) Vue.component('step-button', { props: ['name'], template: "<input :name='name' :value='name' @click='counter += 1' type='button' class='btn btn-secondary' />" }) const progress = new Vue({ el: '#vue-listing', data: { counter: 0, stepList: [ {id: 0, text: 'Basics'}, {id: 1, text: 'Location'}, {id: 2, text: 'Images'}, {id: 3, text: 'Other'} ] }, methods: { addProgress: function() {return true}, // todo delProgress: function() {return true} // todo } }) })

then I have my form

<div id="vue-listing"> <!-- Display the progress through the form --> <ul class="text-center" id="listing-progressbar"> <step-item v-for="item in stepList" :step="item" :key="item.id"></step-item> </ul> <fieldset> Step 1 <step-button name="Next"></step-button> </fieldset> <fieldset> Step 2 <step-button name="Previous"></step-button> <step-button name="Next"></step-button> </fieldset> </div>

Right now I'm stuck on how to get the next and previous buttons to add or remove active from the current step. Eventually I will also need to hide and display the <fieldset> elements depending on the step.

Any help is much appreciated!

Thanks

Categories: Software

Vue.js updating content of an array

Sat, 2017-09-09 15:32

I have an array (feedListBox) which i assigned to my feeds object of data. When i update feedListBox array, Vue.js does not detect it. Therefore i use a fixFeedArray method in my script js file (myApp.fixFeedArray()). It works really fine, but i wonder if there is another way to do it without using any function in my script file. I mean automatically.

var myApp = new Vue({ el: '#my-App', data: { feeds: feedListBox, }, methods: { fixFeedArray: function fixFeedArray() { this.feeds = feedListBox; } } });
Categories: Software

vue-i18n doesn't update locale after integrating vuex

Sat, 2017-09-09 14:41

I'm still new to Vue, but I feel like I'm almost getting the hang of it.. I managed to create an app that could translate to different languages where the content was loaded from LANG.json files.. the problem was that whenever I changed to a new view then it would turn back to the original translation..

So I tried to integrate Vuex to my application, but I can't seem to get it to work..

I believe this is all the relevant code:

src/i18n/index.js

import Vue from 'vue' import VueI18n from 'vue-i18n' import store from './../store' Vue.use(VueI18n) export default new VueI18n({ locale: store.state.Language, messages: { 'en': require('./en.json'), 'cn': require('./cn.json') } })

src/store/index.js

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const actions = { changeLanguage: ({ commit }, data) => commit('changeLanguage', data) } const mutations = { changeLanguage (state, data) { this.state.Language = data.lang } } const getters = { getLanguage: state => state.Language } const state = { Language: 'en' } export default new Vuex.Store({ state, getters, actions, mutations })

src/main.js

[...] import store from './store' import i18n from './i18n' [...] new Vue({ el: '#app', router, store, i18n, render: h => h(App) })

src/components/randomfile.js

<template> [...] <button v-on:click="en">English</button> <button v-on:click="cn">Chinese</button> </template> <script> export default { name: 'navFooter', data () { return { } }, methods: { en: function () { console.log('change lang') this.$store.dispatch('changeLanguage', 'en') // this.$i18n.locale = 'en' }, cn: function () { this.$store.dispatch('changeLanguage', 'cn') // this.$i18n.locale = 'cn' } } } </script>

I'm guessing the problem is either related to this line: locale: store.state.Language, or because I'm doing something wrong with the dispatch, because in one of my views I write {{$store.state.Language}}, which renders to en on page load, but disappears after I click the buttons that call the methods for dispatching.

I call the translations with {{ $t('views.home.title') }} but I'm pretty sure that's still the way they should be called after integrating vuex (store), and the translations do appear as they should, they just don't update after clicking the buttons that dispatch changeLanguage.

Any help would be much appreciated

Categories: Software

Vue.js populating array in data()

Sat, 2017-09-09 13:39

I'm having trouble populating an array in data(). I'm simply pulling from a users JSON object(10 users), which is the same structure as randomapi

<template> <div class='row'> <ul> <li v-for="u in users"> Name : {{u.name}} <br> Email: {{u.email}} </li> </ul> </div> </template>

When the data is received, i loop through and populate a resultsArray, when it finishes, the users[] is equal to the resultsArray

<script> export default { data() { return { users: [] } }, methods: { getUsers() { this.$http.get('./playground/users.json') .then(response => { return response.json() }) .then(data => { const resultArray = [] for(let key in data){ resultArray.push(data[key]) } this.users = resultArray console.log(this.users) }) } }, created(){ this.getUsers() } } </script>

It's printing the following: Name : Email:

Categories: Software

how to change css of a tag on the basis of data?

Sat, 2017-09-09 13:22

I am building a spa in vuejs and I want to change the color of my text on the basis of data I recieved,if i get pending status it should be grey and if submitted then green and if rejected then red and so on.

Categories: Software

Workbox: cannot cache all files when build project

Sat, 2017-09-09 12:39

I use Vuejs and I use workbox-webpack-plugin in order to make my site offline, I want to cache a folder which contains all my files (3 files) like picture below, but when I build my project(using Laravel-mix). The main.js (which contains everything of Vue) cannot be cached in service-woker.js. I tried some ways to fix that but those didn't work. Does anybody face this issue, do you have any solution, many thanks!

->>picture-description

Categories: Software

Pages