Vuejs

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

Need help resolving "[WDS] Disconnected" using vueJS and vue-cli

Fri, 2017-07-21 07:38

I am new to VueJS and am working some simple code to understand how to handle components. I am using a simple-webpack bundler in vue-cli. Right now all I have is a simple template... (App.vue)

<template> <h1>Server Status: Critical!</h1> <template>

and this simple javascript file (main.js)

import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', render: h => h(App) })

I can see whole thing rendered at localhost:8080, but it is throwing a chain of errors at me. This following object...

[WDS] Disconnected! 40:45:10 log webpack-internal:///40:45:10 close webpack-internal:///40:130:3 socket/sock.onclose webpack-internal:///94:15:4 EventTarget.prototype.dispatchEvent webpack-internal:///21:51:5 SockJS.prototype._close/< webpack-internal:///64:356:5

followed by

[HMR] Waiting for update signal from WDS... 41:49:2 //and [WDS] Hot Module Replacement enabled. 40:41:10

Any idea whats going on?

Categories: Software

Can't set background color on body for Framework7 + Vue App

Fri, 2017-07-21 07:28

For some reason I am unable to set the background color by simple using

body { background-color: red; }

Inside off my App.vue file.

I can change the background color by using page-content:

.page-content { background-color: red; }

But this is a bad hack because it also messes up my panels and other components.

Is there a sure-fire way to set background color for F7+Vue apps?

Categories: Software

VUE with JSONP, always shows SyntaxError: Unexpected token?

Fri, 2017-07-21 07:00

I rebuild my code from Angular to Vue. and I meet a strange problem.

for Angular version, it is running correct:

var hq_str_fx_susdcad; function getRate(){ $http.jsonp("http://hq.sinajs.cn/list=fx_susdcad"); if(hq_str_fx_susdcad != undefined){ console.log(hq_str_fx_susdcad); } $interval(getRate,3000,1); }

it will get data from http://hq.sinajs.cn/list=fx_susdcad each 3 seconds, and show the value if it is not undefined.

the results is :

var hq_str_fx_susdcad="12:42:35,1.2601,1.26018,1.2589,23.7,1.25876,1.26051,1.25814,1.2601,美元兑加拿大元即期汇率,0.1,0.0012,0.001883,Dukascopy Bank,1.37937,1.25404,-+--++-+,2017-07-21";

for Vue version.

var vm = new Vue({ el:'.container', data:{ hq_str_fx_susdcad:''; }, methods: { autoReload: function(){ console.log("get rate") this.$http.jsonp('http://hq.sinajs.cn/list=fx_susdcad', function(data) { console.log(data) } ); } }, mounted(){ this.autoReload(); } })

what ever I setup. it always shows that:

Uncaught SyntaxError: Unexpected token ?

Please kindly help to check how to make it works. BTW, I cannot change any part of server http://hq.sinajs.cn/ . Great thanks.

Categories: Software

How to make auto number in php?

Fri, 2017-07-21 04:00

I try to generate auto number v-bind:class="{ 'active' : isSelected(<?php echo $no; ?>) }" v-on:click="selected = <?php echo $no; ?>" which is the list getting from database but the return just get 1 for all of list what I want is 1,2,3,4

here my code

<div class="list-group" id='listGroup'> <?php include 'dismin/pages/koneksi.php'; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; $start_from = ($page-1) * 12; $sql = "SELECT * FROM tbl_album where status='process' ORDER BY albumid DESC LIMIT $start_from, 12"; $rs_result = mysql_query ($sql); ####### Fetch Results From Table ######## while ($row = mysql_fetch_assoc($rs_result)) { $no=1; $aid=$row['albumid']; $aname=$row['name']; ?> <a href="gallery.php?id=<?php echo $aid; ?>" class="list-group-item" v-bind:class="{ 'active' : isSelected(<?php echo $no; ?>) }" v-on:click="selected = <?php echo $no; ?>"><?php echo $aname; ?></a> <?php $no++; } ?> </div>

How do I fix this?

Categories: Software

Resources to beutify .vue files on Atom

Fri, 2017-07-21 03:34

Im starting up with Vue.js. The first problem I've run into is that my IDE (Atom) doesn't beautify my .vue files. Its all just white text.

After some searches I came across this git ptoject but have had little success implementing it.

Any developers know of any resources for achieving a nice looking .vue file format?

Categories: Software

Deploy a vue cli site to s3

Fri, 2017-07-21 01:02

I am trying to deploy a static website to an s3 bucket. I built my site using the webpack template from vue-cli

When I build the site there is a note that:

Tip: built files are meant to be served over an HTTP server. Opening index.html over file:// won't work.

Indeed there are no script tags in index.html but there is a comment that:

<!-- built files will be auto injected -->

If I add a path to the JS build file build/build.js I get that error that require cannot be found.

Is there a way to serve this site via s3? If so, how? Thank you

Categories: Software

VueJS/AdonisJs image upload and usage

Fri, 2017-07-21 00:16

I'm building a webapp that needs to display some images, the frontend is build with VueJS and the backend is build with AdonisJS.

I'm currently having a problem that I'm uploading images from my frontend to my backend. AdonisJS generates a storage path that is local. As example, I upload from my frontend in this form:

Input form

That uses this code on the VueJS side:

let formData = new FormData(); let imagefile = document.querySelector('#file'); formData.append("image", imagefile.files[0]); axios.post('/users/' + this.user.id + "/image", formData, { headers: { 'Content-Type': 'image/*' } })

And on the AdonisJS side:

* updateProfilePicture(request, response) { const image = request.file('image', { maxSize: '20mb', allowedExtensions: ['jpg', 'png', 'jpeg'] }) const userId = request.param('id'); const user = yield User.findOrFail(userId) const fileName = `${new Date().getTime()}.${image.extension()}` yield image.move(Helpers.storagePath(), fileName) if (!image.moved()) { response.badRequest(image.errors()) return } user.profilepicture = image.uploadPath() yield user.save(); response.ok(user); }

Which is working at the moment, but that generates a path that is used by AdonisJS:

ProjectFolder/backend/storage/1500586654324.jpg

VueJS is located in:

ProjectFolder/frontend/*

How can I use my uploaded images in the frontend? Is there some way that these frameworks can be coupled?

Categories: Software

Vue - Vue CLI - API Variables

Thu, 2017-07-20 23:04

What is the best way to set api url's based on current domain location within the Vue Instance? In angular I would be using something similar to Angular Environment However I have not come accross anything similar with Vue or Axios.

In this case my setup is dependent on multiple environments ( local, dev, stage, prod ). All based on domain relationship.

localhost = '/api-call'

dev.domain.com = 'devapi.domain.com'

prod.domain.com = 'prodapi.domain.com'

Any help at all would be incredible!

Categories: Software

How to use complex document text as the input variable in Vue?

Thu, 2017-07-20 23:02

I have this vue:

<script> var starting_point = '{{ form.content.data }}'; vm = new Vue({ el: '#editor', data: { input: starting_point }, computed: { compiledMarkdown: function () { console.log(marked(this.input,{sanitize:true})); return marked(this.input, { sanitize: true }); } }, methods: { update: _.debounce(function (e) { this.input = e.target.value }, 300) } });

This is from the basic example in vue: https://vuejs.org/v2/examples/

It works fine for short sentences. However, once my blog posts - given with {{ form.content.data }} start getting longer and having custom stuff like emojis and line breaks, the javascript variable starts breaking. For instance I see stuff like this:

var starting_point = '# fourthwhat is this? ;o how bout dat. ';

and it says: 2:40 Uncaught SyntaxError: Invalid or unexpected token at the end of the ? I think because theres a line break or something.

So I think I need to stringify this whole thing or somehow make it safe to use as the javascript variable. Is there a good way to do this so that vue can understand it?

Categories: Software

Vue.js/Vuetify - Filter select data based on another select choice

Thu, 2017-07-20 22:54

How can I filter data to populate one select based on the choice of another select? Something like, I choose an state from one select and a second select is loaded with all cities from that specific state. I'm using vue.js and vuetify as framework (with v-select component). I've tried to set a computed property, but even when I choose from first select, the second one doesn't load data.

HTML

Vue.use(Vuetify); var app = new Vue({ el: '#app', data() { return { items: { home_id: null, }, support: { home_province: '', }, options: { opt_province: [{ text: 'British Columbia', value: 1 }, { text: 'Ontario', value: 2 }], opt_city: [{ text: 'Vancouver', value: 1, dependency: 1 }, { text: 'Surrey', value: 1, dependency: 1 }, { text: 'London', value: 1, dependency: 2 }, { text: 'Toronto', value: 1, dependency: 2 }] } } }, computed: { filteredData() { var city = this.options.opt_city; var province = this.support.home_province; for (var i = 0; i < city.length; i++) { if (city[i].dependency != province.value) { city.splice(i); } } return city; }, } }) <script src="https://unpkg.com/vue@2.4.1/dist/vue.js"></script> <link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet" /> <script src="https://unpkg.com/vuetify/dist/vuetify.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet" type="text/css"> <div id="app"> <v-app> <v-card class="grey lighten-4 elevation-0"> <v-card-text> <v-container fluid> <v-layout row wrap> <v-flex xs4> <v-flex> <v-subheader>Origin Province</v-subheader> </v-flex> <v-flex> <v-select :items="options.opt_province" v-model="support.home_province" label="Select" class="input-group--focused" single-line> </v-select> </v-flex> </v-flex> <v-flex xs4> <v-flex> <v-subheader>Origin City</v-subheader> </v-flex> <v-flex> <v-select :items="filteredData" v-model="items.home_id" label="Select" class="input-group--focused" single-line autocomplete> </v-select> </v-flex> </v-flex> </v-layout> </v-container> </v-card-text> </v-card> </v-app> </div>

Here it is jsfiddle link: https://jsfiddle.net/vcmiranda/tkkhwq6m/

Thanks.

Categories: Software

API 404 using VueJs, ExpressJs and Mongoose

Thu, 2017-07-20 22:08

So I am getting a 404 error when my app is trying to connect to my api

I have created an api which works fine, as all data is shown when I access 'http://localhost:3000/api/users'

However, when I access the data through my Vue app, I get a 404:

GET http://localhost:8080/api/users 404 (Not Found)

Code below:

Server.js

var express = require('express'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var users = require('./routes/users.js'); //routes are defined here var app = express(); //Create the Express app var port = process.env.PORT || 3000; var mongoUri = 'mongodb://foo'; mongoose.connect(mongoUri); //configure body-parser app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api', users); //This is our route middleware app.listen(port, function () { console.log('listening to port ' + port) }); module.exports = app;

Home.vue

<script> import axios from 'axios'; export default { data() { return { quote: '' } }, created() { axios.get('/api/users') .then((res) => { console.log(res.data); this.quote = res.data; }) .catch(error => { console.log("error", error); }); }, } </script>

Users.js

var Users = require('../models/users.js'); var express = require('express'); var router = express.Router(); router.route('/users') // Get all users .get(function(req, res) { Users.find(function(err, users) { if (err) { return res.send(err); } res.json(users); }); });

webpack.config.js

output: { path: __dirname + '/build/', publicPath: 'build/', filename: 'build.js' },

What am I doing wrong. Can I assume its something to do with my server.js?

Categories: Software

Calling 'this' inside of firebase once function

Thu, 2017-07-20 22:00

So I am creating a Vuejs application and I am trying to fetch firebase data on component mount. That is working, but I try to write the value into a vuejs data property. For this I would only call this.property = snapshot.val(); inside the firebase function (see code below) but that is not working: this is undefined

So my code just is:

export default { data() { return { imageList: "No images!" } }, mounted() { if (!firebase.apps.length) { // Initialize Firebase var config = { ... }; firebase.initializeApp(config); var database = firebase.database(); var ref = database.ref("images").orderByChild("date"); firebase.database().ref("images/").once('value').then(function(snapshot) { this.imageList= snapshot.val(); }); } } }

I tried calling this.imageList= snapshot.val(); outside of the function with a variable to store the value, and 'this' wasn't undefined anymore, but the data wasn't there because the request hasn't finished yet.

So basically I want to get the snapshot.val(); into this.imageList!

Thanks in advance.

Categories: Software

isset not working with AJAX

Thu, 2017-07-20 20:53

No matter what I've tried, isset doesn't work when I make a post call with Vue Resource. It only works when I turn off preventDefault and go directly to the PHP page.

JS:

this.$http.post('http://localhost/musicdatabase/addalbum.php', new FormData($('#submitalbum'))) .then(data => console.log(data.body));

PHP:

if(isset($_REQUEST['submit'])){ echo json_encode($_REQUEST); }

HTML:

<form class="col s12" id="submitalbum" method="post" action="addalbum.php"> <div class="row"> <div class="input-field col s6"> <input name="artist" placeholder="Artist" type="text"> </div> <div class="input-field col s6"> <input name="title" placeholder="Title" type="text"> </div> </div> <div class="row"> <div class="input-field col s12"> <input name="genre" placeholder="Genre"> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="released" type="number" name="released" placeholder="Year Released"> </div> <button @click.prevent="addNewAlbum" type="submit" name="submit" class="waves-effect waves-light btn">Submit</button> </div> </form>
Categories: Software

How to pass dynamic argument in vuejs custom directive

Thu, 2017-07-20 20:51
<template> <div> <img v-directive:dynamic_literal /> </div> </template>

E.g. dynamic_literal = 'ok' such that in custom directive:

Vue.directive('directive', { bind(el, binding) { binding.arg // should return 'ok'

How can I use dynamic_literal as a variable or a constant whose value should be assigned under data or prop.

I tried with v-directive:{{dynamic_literal}} and :v-directive="dynamic_literal" but no use.

Thanks in advance!

Categories: Software

Vue Trigger watch on mounted

Thu, 2017-07-20 20:50

I have a vue component below that I want to watch to trigger on when it's getting mounted. How do I do that?

Vue.component('check-mark', { name: 'check-mark', template: ` <input :value="value"> `, props: { value: { type: String, required: true, }, }, mounted: async function () { //trigger this.value watch() here }, watch: { value: function (value) { if (value == 'Y') { this.class = 'checked'; } else { this.class = 'unchecked'; } }, }, });
Categories: Software

How to divide Vue.js code?

Thu, 2017-07-20 20:15

I'm discovering that I find Vue.js extremely confusing and even frustrating to work with: I have a Node.JS project with WebPack that has HTML, JS and CSS files (see the code below). When I try to execute the JS as written, it works. However, it has the flaw that the Vue.material.setCurrentTheme('orange'); JS line sets the theme globally as I understand it, which is undesirable.

To fix this, I figured I could remove the JS line above and add a md-theme="orange" attribute to the <md-toolbar> element in the HTML.

This results in the theme not being applied at all, as well as an innocent looking warning in the browser JS console: The theme 'orange' doesn't exists. You need to register it first in order to use. I've figured out that this basically means that the JS is loaded too late and thus when the <md-toolbar> element is loaded the theme is not yet defined.

Ok fair enough, so I change the $(document).ready(function () { ... }); JS block to remove the waiting for the document to be ready, so that only the var App = ... and the theme registration remain, and live on the top-level of the JavaScript file. Now I get a hard error in the browser JS console: client.gen.js:16329 [Vue warn]: Cannot find element: #AvApp

I have 2 questions about this:

  1. How do I fix this? The docs have been no help so far.

  2. Why is Vue.JS defined to need circular dependencies like that, at least when using WebPack? It makes totally no sense whatsoever. In fact this seems to have negative value as it is actively preventing me from getting work done rather than helping me.

HTML:

<!doctype html> <html> <head> <!-- Use Roboto and Google Icons from Google CDN --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Load the generated client code --> <script src="./client.gen.js"></script> <title>Foo</title> <link rel="shortcut icon" href="img/favicon.png" type="image/x-icon"> <link rel="icon" href="img/favicon.ico" type="image/x-icon"> </head> <body > <div id="AvApp"> <!-- nav bar --> <md-toolbar> <md-button class="md-icon-button md-raised md-accent"> <md-icon>more_vert</md-icon> </md-button> <h1 class="md-title center">Foo</h1> <md-button class="md-icon-button md-raised md-primary"> <md-icon>more_vert</md-icon> </md-button> </md-toolbar> <!-- main content --> <div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, rerum? Error sunt, aperiam dolores, atque expedita molestiae tenetur. Quis eveniet accusamus velit explicabo adipisci reiciendis modi eaque quas, officia excepturi. </p> </div> </div> </body> </html>

JS:

/*jshint sub:true, esversion: 6 */ import d3 from 'd3'; import $ from 'jquery'; import _ from 'lodash'; import moment from 'moment'; import q from 'q'; import Vue from 'vue'; import VueMaterial from 'vue-material'; import './amplify-viz.css'; import 'vue-material/dist/vue-material.css'; Vue.use(VueMaterial); function log(msg) { console.log(`\n[CLIENT] ${msg}`); } $(document).ready(function () { var App = new Vue({ el: '#AvApp' }); Vue.material.registerTheme({ default: { primary: { color: 'light-green', hue: 700 }, accent: 'red', background: '#263238' }, teal: { primary: 'blue', accent: 'pink', background: 'yellow' }, orange: { primary: { color: 'orange', hue: 700 }, accent: { color: 'deep orange', hue: 900 } } }); Vue.material.setCurrentTheme('orange'); });

CSS:

.center { text-align: center; flex: 1; }
Categories: Software

Show data instead of object in form value

Thu, 2017-07-20 19:06

I've got a vue.js component that looks like this:

<template> <div> <input type="hidden" v-for="select in selected" :name="prpName + '[]'" :value="select"> <multiselect v-model="selected" </multiselect> </div> </template>

I use this in blade:

<multiselect></multiselect>

The problem now is that when I submit the form in my request I see this:

"relations_internal" => array:1 [▼ 0 => "[object Object]" ]

But I want not an object but the real data. I know this is a newbie question but I can't figured it out.

Categories: Software

Vue router - cannot load component dynamically - Unexpected Token

Thu, 2017-07-20 17:26

I am trying to dynamically load the Login component for my login route. When building webpack I get:

SyntaxError: Unexpected Token

The Login.vue component works fine if I import and assign it the same way I do the Home route.

I'm baffled because I believe this code should work based on this blog.

The line that fails below is:

component: () => import('../components/Login.vue'), router.js import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../components/Home.vue' Vue.use(VueRouter) export default new VueRouter({ mode: 'history', routes: [ { path: '/', name: 'home', component: Home, meta: { permission: "anonymous", }, }, { path: '/login/', name: 'login', component: () => import('../components/Login.vue'), meta: { permission: "anonymous", }, }, ], })
Categories: Software

vue.js: v-model not working for select with v-for

Thu, 2017-07-20 17:12

I have started using vue, so this might be really easy...

Here's my scenario:

var app = new Vue({ el: "#app", data: { utilizador:{ nome:"Luis Abreu", funcoes:[ { secretaria: {idSecretaria:2,nome:"YYY"} } ]}), secretarias: [{idSecretaria:1,nome:"XXX"},{idSecretaria:2,nome:"YYY"},{idSecretaria:3,nome:"Tests 2"}] }

});

And I have something like this for generating the list of funcoes in the HTML:

<tr v-for="(f, pos) in utilizador.funcoes"> <td> <select class="form-control" v-model="f.idSecretaria"> <option v-for="s in secretarias" :value="s.idSecretaria"> {{s.nome}} </option> </select> </td> </tr>

As you can see, the dropbox is being filled from a data property (and that part is working well). Now, the problem is that the select does not show anything selected.

How can I solve this?

Thanks.

Categories: Software

Vue resource inside Vuex action - "this is null" error

Thu, 2017-07-20 17:09

I am trying to make a GET call from inside a store action. However my Vue.http.get() call throws a TypeError "this is null".

I am at a total loss, and I haven't found anyone else with this specific issue elsewhere. Any help would be appreciated. Thanks

Walkthrough
  1. User navs to /login/
  2. Submits login
  3. Authenticated and token received
  4. Dispatches action to save token and retrieve profile
  5. Error occurs when trying to use Vue.http inside action
Login.vue methods: { submit() { this.$http.post( this.loginEndpoint, this.object ).then(response => { this.$store.dispatch({ "type": "auth/save", "token": response.body.key, }).then(() => { this.$router.push({name: "home"}) }).catch(error => { console.log(error) }) }).catch(error => { console.log(error) }) } } Store import Vue from 'vue' import Vuex from 'vuex' import Auth from '../stores/auth.js' // plugins Vue.use(Vuex) export default new Vuex.Store({ modules: { auth: Auth, }, }) auth.js - store module import Vue from 'vue' ... save: (context, payload) => { return new Promise((resolve, reject) => { const url = "/rest-auth/user/" context.commit('setToken', { token: payload.token, }) localStorage.setItem("token", payload.token) console.log("get user profile") // *** Error below calling Vue.http.get *** // TypeError: this is null Vue.http.get(url).then(response => { console.log("Profile received") context.commit('setProfile', { profile: response.body, }) localStorage.setItem("profile", response.body) resolve() }).catch(error => { reject(error) }) }) }
Categories: Software

Pages