Vuejs

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

Setting a value in v-if block

Wed, 2017-07-19 07:55

How do I use v-if to do two things

  1. Show The message and 2) set message.hasSublocationOutage to true.

So if there is an outage show the message and set the flag to true message.hasSublocationOutage Or pass true to a method

<div v-if="!subLocation.outageTag.length - 1"> There is a problem </div>
Categories: Software

Append new Item to a list in Vue 2

Wed, 2017-07-19 07:39

I have a very simple form which gets name and age from user and add this to a list.

You can check that on JSFiddle.

Here is HTML :

<div id="app"> <ul> <li v-for="user in users">{{ user.name +' '+ user.age }}</li> </ul> <hr> <form v-on:submit.prevent="addNewUser"> <input v-model="user.name" /> <input v-model="user.age" /> <button type="submit">Add User</button> </form> </div>

Here is Vue code:

new Vue({ el: '#app', data: { users: [{name:"Mack", age:20}], user: {name:"", age:0} }, methods: { addNewUser() { this.users.push(this.user); } } });

The Problem

The problem is where I trying to add more than one user to the list. As you can see, when I type new value for the new user, previous values of recently added users change too!

How can I fix it?

Categories: Software

How to pass props using slots from parent to child -vuejs

Wed, 2017-07-19 04:48

I have a parent component and a child component.

The parent component's template uses a slot so that one or more child components can be contained inside the parent.

The child component contains a prop called 'signal'.

I would like to be able to change data called 'parentVal' in the parent component so that the children's signal prop is updated with the parent's value.

This seems like it should be something simple, but I cannot figure out how to do this using slots: Here is a running example below:

const MyParent = Vue.component('my-parent', { template: `<div> <h3>Parent's Children:</h3> <slot :signal="parentVal"></slot> </div>`, data: function() { return { parentVal: 'value of parent' } } }); const MyChild = Vue.component('my-child', { template: '<h3>Showing child {{signal}}</h3>', props: ['signal'] }); new Vue({ el: '#app', components: { MyParent, MyChild } }) <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <my-parent> <my-child></my-child> <my-child></my-child> </my-parent> </div>

Categories: Software

How can I "while loop" an Axios GET call till a condition is met?

Wed, 2017-07-19 04:26

I have an API that returns a list of replies (limit 5 replies per call) for a message board thread. What I am trying to do, is look for a specific reply uuid in the response. If not found, make another AXIOS GET call for the next 5 replies.

I want to continue this loop until the UUID is called or the AXIOS GET call comes back with no results.

Example API Request:

http://localhost:8080/api/v2/replies?type=thread&key=e96c7431-a001-4cf2-9998-4e177cde0ec3

Example API Reponse:

"status": "success", "data": [ { "uuid": "0a6bc471-b12e-45fc-bc4b-323914b99cfa", "body": "This is a test 16.", "created_at": "2017-07-16T23:44:21+00:00" }, { "uuid": "0a2d2061-0642-47eb-a0f2-ca6ce5e2ea03", "body": "This is a test 15.", "created_at": "2017-07-16T23:44:16+00:00" }, { "uuid": "32eaa855-18b1-487c-b1e7-52965d59196b", "body": "This is a test 14.", "created_at": "2017-07-16T23:44:12+00:00" }, { "uuid": "3476bc69-3078-4693-9681-08dcf46ca438", "body": "This is a test 13.", "created_at": "2017-07-16T23:43:26+00:00" }, { "uuid": "a3175007-4be0-47d3-87d0-ecead1b65e3a", "body": "This is a test 12.", "created_at": "2017-07-16T23:43:21+00:00" } ], "meta": { "limit": 5, "offset": 0, "next_offset": 5, "previous_offset": null, "next_page": "http://localhost:8080/api/v2/replies?_limit=5&_offset=5", "previous_page": null }

The loop would call an AXIOS GET on the meta > next_page url until either the uuid is found in the results or the meta > next_page is null (meaning no more replies).

Categories: Software

File input on change in vue.js

Wed, 2017-07-19 02:19

Using plain HTML/JS, it is possible to view the JavaScript File objects of selected files for an input element like so:

<input type="file" id="input" multiple onchange="handleFiles(this.files)">

However, when converting it to the 'Vue' way it doesn't seem to work as intend and simply returns undefined instead of returning an Array of File objects.

This is how it looks in my Vue template:

<input type="file" id="file" class="custom-file-input" v-on:change="previewFiles(this.files)" multiple>

Where the previewFiles function is simply the following (located in methods):

methods: { previewFiles: function(files) { console.log(files) } }

Is there an alternate/correct way of doing this? Thanks

Categories: Software

How to correctly use Vue JS watch with lodash debounce

Wed, 2017-07-19 01:22

I'm using lodash to call a debounce function on a component like so:

... import _ from 'lodash'; export default { store, data: () => { return { foo: "", } }, watch: { searchStr: _.debounce(this.default.methods.checkSearchStr(str), 100) }, methods: { checkSearchStr(string) { console.log(this.foo) // <-- ISSUE 1 console.log(this.$store.dispatch('someMethod',string) // <-- ISSUE 2 } } }
  • Issue 1 is that my method checkSearchStr doesn't know about foo
  • Issue 2 is that my store is undefined as well

Why doesn't my method know this when called through _.debounce? And what is the correct usage?

Categories: Software

How to do center layout like this in Vuetify or Material Design?

Wed, 2017-07-19 01:19

I have this layout as of now: enter image description here

But my end goal is this, main content is centered. toolbar and page title is centered but a little bit on the left:

enter image description here

Here's my template layout in Vuetify/Vue

<v-tabs dark fixed centered> <v-toolbar extended class="cyan" dark> <v-toolbar-side-icon></v-toolbar-side-icon> <v-spacer></v-spacer> <v-btn icon> <v-icon>search</v-icon> </v-btn> <v-btn icon> <v-icon>more_vert</v-icon> </v-btn> <v-toolbar-title slot="extension" class="display-3">Share My Pic</v-toolbar-title> </v-toolbar> <v-tabs-bar slot="activators" class="cyan "> <v-tabs-slider class="yellow" >Slider</v-tabs-slider> <v-tabs-item v-for="i in tabArray" :key="i" :href="'#tab-' + i"> {{i}} </v-tabs-item> </v-tabs-bar> <v-tabs-content v-for="i in 3" :key="i" :id="'tab-' + i" > <v-card flat> <v-card-text>{{ text }}</v-card-text> </v-card> </v-tabs-content> </v-tabs>

Kindly help pls. Any good advice to move me in the right direction is appreciated.

-Adi

Categories: Software

how to execute jQuery code when route is visited?

Wed, 2017-07-19 00:41

I have an off-canvas menu that gets drawn in once a Vue route is clicked using jQuery, like so:

$('.order-drawer').show(); $('body').toggleClass( 'order-drawer-open' );

My route is very simple and is displayed as follows:

<router-link to="/order" exact class="order-drawer-toggler"> <a>Order Now</a> </router-link> <router-view></router-view>

Now, how can I make sure that when http://test.dev/test/#/order is viewed in the browser, that then my jQuery calls are getting executed? How can I call a function onload of a route view?

Categories: Software

Importing exif-js library Uncaught ReferenceError: EXIF is not defined error

Wed, 2017-07-19 00:40

I am using vue in a rails application and am trying to import the exif-js library into my script in order to access the global EXIF variable to use as such

var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));

I have downloaded the package by following these yarn instruction.

yarn add exif-js -- save

I realize I need to use the javascript import to include it into my scripts and have tried

<script> import EXIF from 'exif-js' previewPhoto() { var reader = new FileReader() reader.onload = () => { var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result)); } </script>

and other variances such as import 'exif-js', however I keep getting Uncaught ReferenceError: EXIF is not defined error. How do I successfully import the library so that I can use it in my scripts.

Categories: Software

Behavior of events, and the $event variable in Vue.js

Tue, 2017-07-18 23:38

Using vue.js I am studying DOM manipulation and responses from events. I've noticed that on many events you can simply call a function. Here I simply increase a counter with each click of a button. No arguments are passed. This makes sense to me since there is no data needed by the function.

<div id="content"> <button @click="countUp()">Counter Control</button> <p>{{count}}</p> </div> <script> new Vue({ el: '#content', data: { count: 0 }, methods: { countUp: function(){ this.count ++; } } }) </script>

But now, with a slightly more complicated method at becomes necesary to provide the 'event' argument. The following div tracks the mousemove event and updates the cursors x and y coordinates in real time via methods.

<div @mousemove="updateCoords($event)" style="height:400px;width:400px;border:2px solid black;"> {{x}} {{y}} </div> //the following properties are set up in the data{} object x: 0, y: 0 //this method is added to the methods{} object and is passed event updateCoords: function(event){ this.x = event.clientX; this.y = event.clientY; }

Here this function does not work if event is not passed. It makes sense to me that we would pass something here since X and Y coordinates are dependent on the last location of the event. But how is this data accessed? Do certain events track and store data within themselves?

Finally it seems to make no difference if I pass my method the special $event variable or not. Calling...

@mousemove="updateCoords($event)" //is the same as @mousemove="updateCoords()"

Does view automatically know that an incoming event argument is $event? Or is $event important to use in some other particular case??

Thanks for reading

Categories: Software

Is there a way to capture events emitted by multiple child components in vuejs?

Tue, 2017-07-18 23:12

I have a parent component which has multiple child components

<grid> <cell></cell> <cell></cell> <cell></cell> </grid>

My cell components emit an event with payload saying it is being edited this.$emit('editing',cellId)

I know I can capture the event like <cell @editing="do something"></cell> or capture using EventBus.$on('editing'), I do not want to use root listener as well this.$root.$on('editing')

But because its the parent component, how can i listen to event of 'editing' when the parent component is mounted

mounted: function(){ this.$on('editing',dosomething) }

why am I not able to add listen when the parent component is mounted?

Categories: Software

vue-chart.js : how can i use data from store (dispatch) directly inside component?

Tue, 2017-07-18 22:45

As i failed miserably at using C3 with vue, i went for vue-chart.js, which seems promising..

My problem is.. i want to do a dispatch to the store to fetch my api data, and use this as the datasource of my pie chart, and i haven't found out how to do this either through docs or googling..

My guess is that by using "mapgetters" in computed, and using "$store.dispatch()" in mounted, the data is not ready when the chart is rendered..

Anyone know how to do this ?

See my example below :

<script> import * as types from '../store/mutationtypes' import { mapGetters, mapActions } from 'vuex' import { Pie } from 'vue-chartjs' export default Pie.extend({ mounted () { this.$store.dispatch('getStatisticsForOrderStatus'), this.renderChart({ labels: [this.statOrderstatus.key], // labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], datasets: [ { label: 'Ticketstatus', backgroundColor: '#f87979', data: [this.statOrderstatus.doc_count] } ] }) }, computed: { ...mapGetters(["statOrderStatus"]) }, }) </script> Data looks like this : { "key": "Fornyet ikke lastet ned", "doc_count": 7793 }, { "key": "Bekreftet levert til mobil", "doc_count": 5239 }, { "key": "Betaling kansellert", "doc_count": 1035 },

Categories: Software

vuejs prototype array not being watched

Tue, 2017-07-18 22:07

in my vuejs program i am trying to make a global instance of an alert/notification system. This would be at the rootmost instance of the app. and then my plan was to push to an array of objects and pass that through to the component. This only half works.

in my app.vue i have

<template> <div id="app"> <alert-queue :alerts="$alerts"></alert-queue> <router-view></router-view> </div> </template>

in my main.js i have

exports.install = function (Vue, options) { Vue.prototype.$alerts = [] }

and my alert_queue.vue is

<template> <div id="alert-queue"> <div v-for="alert in alerts" > <transition name="fade"> <div> <div class="alert-card-close"> <span @click="dismissAlert(alert)"> &times; </span> </div> <div class="alert-card-message"> {{alert.message}} </div> </div> </transition> </div> </div> </template> <script> export default { name: 'alert', props: { alerts: { default: [] } }, data () { return { } }, methods: { dismissAlert (alert) { for (let i = 0; i < this.alerts.length; i++) { if (this.alerts[i].message === alert.message) { this.alerts.splice([i], 1) } } } } } </script>

I can add to this list now by using this.$alerts.push({}) and i can see they are added by console.logging the results.

The problem is that the component doesn't recognise them unless i manually go in and force it to refresh by changing something in code and having webpack reload the results. as far as i can see, there is no way to do this programatically.... Is there a way to make prototype components be watched like the rest of the application?

I have tried making the root most file have a $alerts object but when i use $root.$alerts.push({}) it doesn't work because $root is readonly.

Is there another way i can go about this ?

Categories: Software

Vue Devtools Chrome Extension Not Working for Local Hostname

Tue, 2017-07-18 20:59

I'm trying to use Vue devtools via the chrome extension, but it's saying that "Vue.js not detected" even though Vue is loaded on the page.

I'm on Chrome version 59.0.3071.115 and have the most up to date extension. I'm developing locally and have a custom hostname e.g. dev-site.com:3000.

I'm running the development version of Vue.js

Categories: Software

Using Vue Components in Moqui Screens

Tue, 2017-07-18 19:54

Is it possible to use VusJS Components into Moqui Screens? I know for sure that you can render Basic HTML but I wasn't able to find a hook for the VueJS app.

The need comes from the following scenario: While form-single widget can be made collapsible, form-list cannot. So I wanted to use vue-collapsible (https://github.com/vue-comps/vue-collapsible) but I don't know where I am supposed to register the component.

If there's no way to use vue, maybe you can help me with my concrete issue.

Categories: Software

Cannot load assets more than once with PreloadJS and Vue.js

Tue, 2017-07-18 17:43

I am trying to create a Vue.js component which would allow me to load (using PreloadJS) and display various EaselJS canvas experiments. The Vue.js component:

  1. Gets created with a HTML canvas and 2 divs for experiment scripts and the EaselJS library
  2. created lifecycle hook: Loads the EaselJS library using PreloadJS (included in the main HTML file)
  3. Stores the EaselJS lib files in the #creatjLib div
  4. Afterwards it loads the experiment script files and stores them in #gameAssets

Here is the component:

<template> <div class="fullscreen"> <canvas id="canvas" class="fill"></canvas> <div id="createjsLib" class="hidden"></div> <div id="gameAssets" class="hidden"></div> </div> </template> <script> import {createjsList} from '../../assets/lists/games.js' import {manifests} from '../../assets/conf.js' export default { props: ['id'], data() { return { game: createjsList[this.id], queue: new createjs.LoadQueue() }; }, methods: { onLibrariesLoaded() { var lib = this.queue.getResult("EaselJS"); var libCont = document.getElementById("createjsLib"); libCont.innerHTML = ""; libCont.appendChild(lib); document.getElementById('gameAssets').innerHTML = ""; var manifest = (this.game.manifest) ? this.game.manifest : '/static/games/' + this.id + '/manifest.json'; this.queue = new createjs.LoadQueue(); this.queue.on("complete", this.onGameAssetsLoaded); this.queue.on("fileload", this.onGameAssetLoaded); this.queue.loadManifest(manifest); }, onGameAssetLoaded(e) { var type = e.item.type; if (type == createjs.LoadQueue.CSS || type == createjs.LoadQueue.JAVASCRIPT) { document.getElementById('gameAssets').appendChild(e.result); } }, onGameAssetsLoaded() { console.log('Assets Loaded'); } }, created() { var manifest = manifests.createjs; this.queue.on("complete", this.onLibrariesLoaded); this.queue.loadManifest(manifest); console.log('created'); } } </script> The Problem

My problem is that this process only works once. I can load the EaselJS library and the experiments files only once, the scripts get correctly executed but once I navigate (vue-router, history mode) home for example and then back to the experiment it fails to even load the library again and crashes in the created lifecycle hook.

Error in created hook: "TypeError: Cannot read property 'observeArray' of undefined"

Console log

I tried using the destroyed and beforeDestroy lifecycle hooks to cancel, delete, reset the PreloadJS queue but nothing I tried works. The error seems to happend somewhere in Vue.js but I am not sure why or how to fix this. I have checked the manifest url and it points to the correct static JSON manifest file.

Any ideas what's going on? What have I missed here? Any advice/help will be appreciated

Categories: Software

Vuejs passing object to other route

Tue, 2017-07-18 16:58

I am a beginner with vuejs and now i am facing an issue:

I have an object in one page, and, when clicked in a "detail" button to view details of this object i want to open another route with detailed infos about this object.

My problem is that i don't want to use route params to send the object to another view in another route because this will show the object in the url neither i want to use localStorage to storage the object.

I was reading about vuex and props, but i don't think i understand really well how to use them in my case :/ , can anybody help me?

Thanks in advance :)

Categories: Software

Adding Vue.js To Rails 5.1 and Unit Tests in Mocha don't work

Tue, 2017-07-18 16:37

Repo is available here: https://github.com/systemnate/vuetesting

I created a rails app by running the command rails _5.1.2_ new vuetesting --webpack=vue

And then added mocha and chai yarn add mocha chai --save-dev

And then created a test directory by running mkdir test/javascript

Then I created a spec file to run... touch app/javascript/App.spec.js

And pasted in the following code:

const chai = require('chai') const expect = chai.expect describe('first test', () => { it('is true', () => { expect(true).to.equal(true) }) })

And added the following to package.json

"scripts": { "test": "mocha test/**/*.spec.js --recursive" }

Now previous yarn test passes. Let's try to implement a Vue specific test.

I run the command yarn add avoriaz mocha-webpack --save-dev

And then modified package.json to use mocha-webpack:

"scripts": { "test": "mocha-webpack test/**/*.spec.js --recursive" }

yarn test still passes.

Now I want to test the single file component. To start with, I added to the top of my test so it looks like this:

import Vue from 'vue'; import App from '../../app/javascript/packs/App.vue'; const chai = require('chai') const expect = chai.expect describe('first test', () => { it('is true', () => { expect(true).to.equal(true) }) })

And then run yarn test and get the following output

yarn test v0.27.5 $ mocha-webpack test/**/*.spec.js --recursive ERROR in ./app/javascript/packs/App.vue Module parse failed: /Users/natedalo/Ruby/vuetesting/app/javascript/packs/App.vue Unexpected token (1:0) You may need an appropriate loader to handle this file type. | <template> | <div id="app"> | <p>{{ message }}</p> @ ./test/javascript/App.spec.js 2:0-53 error Command failed with exit code 1.

Any thoughts on what could be going wrong?

Categories: Software

Vue + php, how send array to props?

Tue, 2017-07-18 16:32

I just started to learn Vue, and I can't understand what for is props? I have simple array in php :

$vegetables = ['apple', 'strawberry', 'banana'];

Now I want it in my blade ( laravel ), but I don't know how to do foreach now with Vue... I tryed to do like this:

<html> <head> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app-7"> <ol> <vegetable-item v-for="item in vegetables" </vegetable-item> </ol> </div> </body> <script> Vue.component('#app7', { props: ['array'], template: '<li>{{ item.text }}</li>' })

It completely doesn't work....

Categories: Software

Sending one time event to child components

Tue, 2017-07-18 14:57

Im struggling to implement something which I think is pretty easy.

In my Vue app I loop through a list. Each list item is a child component. Each list item has an expand/collapse button. That works fine, but I want to be able to close all open items from the parent and I don't seem to be able to get that working as I would like.

The expand/collapse is controlled via a variable called isOpen so

<div v-if="isOpen">Something here</div>

I have tried using a computed property instead of the isOpen and passing props but that issue is I think it needs to act more like an event.

Consider three open list items. If the list items are controlled by a prop, and setting it to false closes the items, when an item is reopened, the prop is still false so therefore will not work a second time. I know I could change it back on the parent, but it seems wrong.

Whats the best way to accomplish this?

Categories: Software

Pages