Vuejs

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

How to make modal box in vue js in <a> tag?

Thu, 2017-08-24 09:44

I am having a list of navbar menu items as like,

<div class="navbar navbar-default menu-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="index.html" class="navbar-brand"><img src="images/logo.png" alt="logo"><span>Sd Residency</span></a> </div> <nav class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="">Rooms</a></li> <li><a href="">Gallery</a></li> <li><a href="">Contact Us</a></li> <li><a href="" id="show-modal" @click="showModal = true">Sign In</a> </li> </ul> </nav> </div> </div>

In the above list, if i click on sign-in menu, a modal box needs to be displayed in which there should also be a sign up option in which if we click on sign up, a another modal box needs to be displayed..

For this, i have started with initial step of using @click,

<li><a href="" id="show-modal" @click="showModal = true">Sign In</a></li>

And,

<modal v-if="showModal" @close="showModal = false"> <h3 slot="header">Sign In</h3> </modal>

And also,

<script type="text/x-template" id="modal-template"> <transition name="modal"> <div class="modal-mask"> <div class="modal-wrapper"> <div class="modal-container"> <div class="modal-header"> <slot name="header"> default header </slot> </div> <div class="modal-body"> <slot name="body"> default body </slot> </div> <div class="modal-footer"> <slot name="footer"> default footer <button class="modal-default-button" @click="$emit('close')"> OK </button> </slot> </div> </div> </div> </div> </transition> </script>

Script,

export default { data(){ return{ showModal: false, } } }

and,

Vue.component('modal', { template: '#modal-template' }) new Vue({ el: '#app', data: { showModal: false } })

It is displaying only the <h3> that shows sign in displays if i click on sign in <a> tag and i am not getting modal box, I don't understand how to do it to get the modal box and i am sure i am wrong with this way. But dont know how to achieve. Kindly help me to achieve getting the modal box while clicking the sign in option.

Categories: Software

How set Vue inputs via phantomjs?

Thu, 2017-08-24 09:13

The code like that:

document.getElementById('email').value = 'login'; document.getElementById('password').value = 'pwd'; document.getElementById('button').click();

does not work because Vue uses v-model value instead of value attribute. Is there a way to change input and model values via javascript in phantomjs?

Notes

  1. Setting attribute v-model for those input do not solve the problem.

  2. Using CSP-compliant-build is not possible, because I can not rebuild project from sources.

  3. Any extension for chrome also can not be used because page is rendered via phantomjs

Categories: Software

VueJS cannot get path after reload or direct link

Thu, 2017-08-24 09:11

I have trouble with VueJS(or with my brains). Ok. I have vuejs-webpack project and this router:

import Vue from 'vue' import Router from 'vue-router' import Main from '@/components/Main' import CreateTravel from '@/components/CreateTravel' import TravelDetail from '@/components/TravelDetail' import Friends from '@/components/Friends' import UserTravels from '@/components/UserTravels' import User from '@/components/User' import Settings from '@/components/Settings' import UserActivate from '@/components/UserActivate' Vue.use(Router); export default new Router({ mode: 'history', routes: [ { path: '/user/activate/:secret', name: 'UserActivate', component: UserActivate }, { path: '/', name: 'Main', component: Main }, { path: "/create", name: "Create", component: CreateTravel }, { path: "/travel/:id", name: "Travel", component: TravelDetail }, { path: "/friends", name: "Friends", component: Friends }, { path: '/user/:id', name: 'User', component: User, children: [ { path: 'travels', name: 'UserTravels', component: UserTravels } ] }, { path: '/settings', name: 'Settings', component: Settings } ] })

And main.js:

// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import VeeValidate from 'vee-validate'; import VueResource from 'vue-resource'; Vue.use(VeeValidate); Vue.use(VueResource); Vue.config.productionTip = false; /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: {App} });

And when I redirect to some link I have 404. Example, after redirect on link http://localhost:8080/user/activate/73e7bcfa-a9d2-4d32-8ddc-697a82bf6363 from email I look "Cannot GET /user/activate/73e7bcfa-a9d2-4d32-8ddc-697a82bf6363". In console browser next:

361d711d-05ef-4c5e-944a-7e511ba104ab:1 GET http://localhost:8080/user/activate/361d711d-05ef-4c5e-944a-7e511ba104ab 404 (Not Found). Thanks for your help

Categories: Software

How do I speed up 'watching' multiple arrays with the same data in vue.js

Thu, 2017-08-24 08:50

A large amount of data (+-15 000 records) is loaded via AJAX which is then used to populate two arrays, one sorted by ID the other by a name. Both the arrays contains the same objects just ordered differently.

The data is displayed in a tree view but the hierarchy can be changed by the user. The tree is virtualised on the first level so only the records displayed + 50% is 'materialized' as vue components.

Supplying both of the arrays as data to a vue instance is very slow. I suspect vue.js is adding observers to the objects twice, or change notifications is sent multiple times, I don't really know.

So only one of the arrays is added to vue the other is used out of band.

Vue slows down the addition of elements to an array a lot. If the array is populated before it is bound to the vue instance it takes +-20s before the tree view is displayed. If I bind it before populating the arrays it takes about +-50s before the tree view becomes usable (the elements are displayed almost instantly). This could be because of notifications going for all these elements added.

  1. Is there a way to add a second array with duplicate data so vue.js watches it for changes, but it doesn't slow vue down as much?

  2. Is there a way to switch watching/notifications of temporarily so elements could be added to an array without the penalty, yet be 'watched' when notifications is switched back on?

I'm not sure that my reasoning behind the slowdowns is correct, so maybe my questions are misguided.

O another thing I need the arrays to be watched and only one of the properties of the elements.

Categories: Software

GraphQL vue apollo query and mutation same view

Thu, 2017-08-24 06:13

I'm just starting to use GraphQL with Apollo and Vue, so it might be a "stupid" question but I can't figure how to do.

How can I do inside the same view, a query to fetch one object, and update it using a mutation

Let's say I have a simple schema

type Product { id: ID! title: String! description: String }

And a vue component

<script> // GraphQL query const ProductQuery = gql ` query($id: ID){ Product(id: $id) { id title description } } `; const UpdateProductQuery = gql ` mutation updateProduct($id: ID!, $title: String!, $description: String) { updateProduct( id: $id, title: $title, description: $description, ) { id } } `; export default { data() { return { Product: {}, }; }, apollo: { Product: { query: ProductQuery, variables() { id: 1234, }; }, }, methods: { updateProduct() { this.$apollo.mutate({ mutation: UpdateProductQuery, variables: { id: this.Product.id, title: this.Product.title, description: this.Product.description, }, }) } } }; </script>

Now how am I supposed to write the template part ? Can I link the Product object to a v-model inside an input ?

<template> <section> <input v-model="product.title"></input> <input v-model="product.description"></input> <button @click="updateProduct">Update</button> </section> </template>

Thanks for your help.

Categories: Software

ESLint code format in Vue

Thu, 2017-08-24 05:37

I created a project with npm and vuejs/vue-cli.

I imported the ESLint extension.

I have eslint entries in my package.json file.

Now when I format my code (right-click, Format Code), it completely disfigures my code.

What do I have to do to get vscode to format according to the ESLint rules?

enter image description here

enter image description here

enter image description here

But on the website, ESLint complains that everything is not formatted correctly, and so it is obviously installed and running in some sense:

enter image description here

Categories: Software

Execute a code after every function is called

Thu, 2017-08-24 04:46

I have a scrolltobottom() function that is run after every function is executed.

How can I refactor the code so that I don't need to type scrolltobottom() everywhere?

Preferably without using Jquery.

async function initBot () { let botui = BotUI('homepage-bot', { vue: Vue }) let scrolltobottom = () => { let ele = document.getElementById('botui') document.body.scrollTop = ele.clientHeight } await botui.message.bot({"Hello"}) await scrolltobottom() await botui.message.bot({"Do you like apple or orange?"}) await scrolltobottom() await botui.message.button({"Orange", "Apple"}) await scrolltobottom() }
Categories: Software

Vue. How to get a value of a "key" attribute in created element

Thu, 2017-08-24 04:30

I try to create a components and get its key for using in axios. Elements created, but I can't get a key. It's undefined

<div class="container" id="root"> <paddock is="paddock-item" v-for="paddock in paddocks" :key="paddock.key" class="paddock"> </paddock> </div> <script> var pItem = { props: ['key'], template: '<div :test="key"></div>', created: function() { console.log(key); } }; new Vue({ el: '#root', components: { 'paddock-item': pItem }, data: { paddocks: [ {key: 1}, {key: 2}, {key: 3}, {key: 4} ] } }) </script>

I try some variants, but no result - @key was empty.

Categories: Software

What does props stands for in javascript frameworks?

Thu, 2017-08-24 03:42

I am Angular2/4 and Vue.js developer. Today, suddenly I was asked from my friend about meaning of props. She asked me what does props stands for in Angular. I couldn't give right answer, so What does props stands for in Javascript? Cheers!

Categories: Software

How to preserve custom component tag names in Vue.js

Wed, 2017-08-23 23:35

I'm using Vue's single-file component spec (*.vue) for custom components in my application. Together with rollup and rollup-plugin-vue, I have observed the output in the DOM, for custom components I have written, to be composed of the equivalent html elements.

For example:

component-a.vue

<template> <span>Hello World</span> </template> <script> export default { name: 'component-a' }; </script>

component-b.vue

<template> <component-a></component-a> </template> <script> import ComponentA from './path/to/component-a.vue'; export default { name: 'component-b', components: { ComponentA } }; </script>

The above example, if component-a is added to the Vue mount component, will render to a the sum of the two component's template contents in the DOM, which in this case is simply a span element:

<span>Hello World<span>

Is it possible to achieve a rendered output in the DOM like the snippet below, such that custom elements' templates are represented in the DOM by tags which preserve their tag names?

<component-b> <component-a> <span>Hello World</span> </component-a> </component-b>
Categories: Software

vue.js render ajax data that contains vue.js syntax

Wed, 2017-08-23 23:15

Vue.js version is: 2.x

Hi. i'm sending ajax request in vue js to other page and get it's source. this source contains vue.js syntax such as events, ... when this source added to property and property added to template, the ajax data source (that contains vue.js syntax) can not be render and can't works properly. for example template is:

<div id="app"> {{{ foo }}} </div>

and app.js is:

var app = new Vue({ el: '#app', data: { foo: 'bar' }, mounted(){ this.$http.get('/media').then(function(response){ data = response.body; Vue.set(app, 'foo', data); }); }, methods: { alertVideoLink: function(event){ alert(event.target.href); } } });

in the above app.js code, ajax request return this code (that is response.body):

<a href="/media/videos" @click.pevent.self="alertVideoLink(event)">Video Link</a>

but this link can't be render and can't works properly! i'm test the render method and some useful hints, but no way found. please help... Thanks

Categories: Software

Call an action from within another action

Wed, 2017-08-23 22:44

I have the following setup for my actions:

get1: ({commit}) => { //things this.get2(); //this is my question! }, get2: ({commit}) => { //things },

I want to be able to call one action from within another, so in this example I want to be able to call get2() from within get1(). Is this possible, and if so, how can I do it?

Categories: Software

register component in vue,js

Wed, 2017-08-23 21:43

I am working on a project in .NET with MVC and Vue.js, at the moment of wanting to use the components I have to declare it as follows:

import Vue from 'vue'; import example from './components/example.vue' import equiposcrear from './components/equipos/crear.vue' import equipos from './components/equipos/index.vue' import cargardiesel from './components/equipos/cargarDiesel.vue' const app = new Vue({ el: '#app', components: { example, equiposcrear, equipos, cargardiesel } })

If i registered as Vue.component('equipos', require('./components/equipos/index.vue'));

At the moment i want to use send the error that the component is not registered

@{ ViewBag.Title = "Equipos"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div id="app"> <equipos></equipos> </div>

What am i doing wrong?

Categories: Software

Proper Way to Call Multiple Mutations in Vuex

Wed, 2017-08-23 21:24

I have the following setup for an action:

myAction: ({commit}) => { commit('mutation1'); commit('mutation2'); commit('mutation3'); },

The thing is, I need mutation1 to for sure run first (which it does most of the time) and I need mutation2 to only run if mutation1 succeeds, and so on for mutation3. Since calling a mutation won't return anything, I'm figuring there has to be a better way to do what I'm trying to do. Is there a best practice for calling multiple mutations that depend on the previous mutation to succeed?

Categories: Software

Vue cannot register coponent if JS file is loaded externally

Wed, 2017-08-23 20:43

I'm using vue in regular js files (not .vue) and inline templates. I got few components that are loaded depend on the subpage. What I wanted to do is to load some global vue variables and vue coponents and then dynamically, using jQuery load additional vue coponents script if some container (eg. #blog) has lenght > 0.

The issue is that Vue is throwing an error that it found the Vue tags but couldn't register the component.

Is there any way of loading dynamically the JS files? I got really big website with a lot of js files that I want to load only on specific subpages. It works perfectly for all jQuery libs but sadly not for Vue components.

Example component below:

Vue.component('blog-entries', { name: "blog-entries", template: require('js/vue/home/blog/blog.html').template, data: function () { return { blog_entries: [ ] } } });

and error:

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in )

load script:

function loadScript(scriptName, callback) { if (!_arr[scriptName]) { _arr[scriptName] = true; var body = document.getElementsByTagName('body')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = scriptName; // then bind the event to the callback function // there are several events for cross browser compatibility // script.onreadystatechange = callback; script.onload = callback; // fire the loading body.appendChild(script); } else if (callback) { callback(); } };
Categories: Software

axios.post not sending auth header (but .get does)

Wed, 2017-08-23 19:50

I am using axios in my Vue project, and one of the calls to my api involves a POST. Both my posts and gets require that the Authorization header be set with my token. All get requests work fine, but putting the exact same headers in axios.post results in a 403.

Here is my axios code:

axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, { withCredentials: true, headers: { 'Authorization': 'Bearer ' + mytoken } }) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error) })

This always results in a 403 error, and checking my request headers show that the Authorization header is never sent. If I change axios.post to axios.get above (and add a GET method to my api code, in addition to the existing POST,OPTIONS), it will execute just fine. I suppose I could leave it this way, but I think it is bad practice to use a GET call when one really is performing a POST. Is there something I am missing about forming a POST request with axios?

Categories: Software

vuex subscribe to individual mutation

Wed, 2017-08-23 19:16

Is it possible to subscribe to an individual mutation?

Instead of:

this.$store.subscribe((mutation, state) => { if(mutation === 'someMutation'){ doSomething() } })

I would like something like this:

this.$store.subscribe('someMutation', state => { doSomething() })
Categories: Software

How do I hide results on an empty query in Laravel + Vue?

Wed, 2017-08-23 19:10

Running Laravel Scout + Algolia with Vue. Got it all working and the searching is nice and fast. However I want to hide the results on an empty query instead of displaying the whole index.

Algolia provides this solution:

var search = instantsearch({ [...], searchFunction: function(helper) { var searchResults = $('.search-results'); if (helper.state.query === '') { searchResults.hide(); return; } helper.search(); searchResults.show(); } }

Here is my search:

//search.blade.php <ais-index app-id="{{ config('scout.algolia.id') }}" api-key="{{ env('ALGOLIA_SEARCH') }}" index-name="dev_users"> <ais-search-box placeholder="Zoek een gebruiker" :autofocus="true"></ais-search-box> <ais-results></ais-results> <script> new Vue({ el: "#search", }) </script>

And here is my app.js

import InstantSearch from 'vue-instantsearch'; Vue.use(InstantSearch);

I can't figure out how to implement the code from the Algolia manual. Can you guys point me in the right direction?

Thanks in advance.

Categories: Software

Vue.js 2 + Firebase getting data to item inner view

Wed, 2017-08-23 19:02

I'm trying to build a little simple content management system.

I'm using Vue.js V2 + Google Firebase + Vue Fire + Vue Router.

What I'm failing to understand how should I pass params to the inner view from home view. I want to click on one of the items on homepage, then open inner view for it. What I tried so far is passing the ['.key'] param through vue-router, then reading it in views/inner.vue like this :

let textRef = database.ref('apps/'+ this.$route.params.appid +'/text') firebase: { paragraphs: textRef } <tbody> <tr v-for="paragraph in paragraphs"> <td>{{paragraph.content}}</td> <td>{{paragraph.time}}</td> <td><span class="glyphicon glyphicon-trash iconClick" aria-hidden="true" v-on:click="removeText(paragraph)"></span></td> </tr> </tbody>

but then it creates undefined new item in the Home view.

What am I doing wrong? I'm fairly new to vue.js/firebase.

Here's my code below.

main.js

import Vue from 'vue' import VueFire from 'vuefire' import router from './router' import App from './App' Vue.config.productionTip = false Vue.use(VueFire) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })

App.vue

<template> <div id="app"> <div class="container"> <h1>{{titleMain}}</h1> <router-view></router-view> </div> </div> </template> <script> export default { name: 'app', data () { return { titleMain: 'LiveText v1.0 for lrytas.lt' } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; margin-top: 60px; } h1 { margin-bottom: 60px; } .iconClick, .appsList { cursor: pointer; } </style>

views/inner.vue

<template> <div> <h2>{{msg}}</h2> <h3>{{$route.params.app['.key']}}</h3> <h5>{{$route.params.app.created}}</h5> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{$route.params.app.name}}</h3> </div> <div class="panel-body"> <table class="table table-hover"> <thead> <tr> <th>Paragrafas</th> <th>Laikas</th> <th></th> </tr> </thead> <tbody> <tr v-for="paragraph in paragraphs"> <td>{{paragraph.content}}</td> <td>{{paragraph.time}}</td> <td><span class="glyphicon glyphicon-trash iconClick" aria-hidden="true" v-on:click="removeText(paragraph)"></span></td> </tr> </tbody> </table> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Pridėti paragrafą</h3> </div> <div class="panel-body"> <form id="form" class="form-inline" v-on:submit.prevent="addText"> <div class="form-group"> <label for="appTitle">Pavadinimas:</label> <textarea type="text" id="appTitle" class="form-control" v-model="newParagraph.content"></textarea> <input type="submit" class="btn btn-primary" value="Kurti"> </div> </form> </div> </div> </div> </template> <script> import Firebase from 'firebase' import toastr from 'toastr' let database = Firebase.database() let textRef = database.ref('apps/-KsEMtgKSeVtA9_rSgWD/text') export default { name: 'hello', data () { return { msg: 'Inner page!', newParagraph: { content: '', time: this.getTime() } } }, methods: { addText: function () { textRef.push(this.newParagraph) this.newParagraph.content = '' toastr.success('Paragrafas sėkmingai pridėtas!') }, removeText: function (paragraph) { console.log(paragraph) textRef.child(paragraph['.key']).remove() toastr.success('Paragrafas sėkmingai pašalintas!') }, getTime: function () { var date = new Date() var dateFormated = date.toLocaleDateString('lt') var timeFormated = date.toLocaleTimeString('lt', {hour12: false, hour: '2-digit', minute: '2-digit'}) var current = dateFormated + ' ' + timeFormated return current } }, firebase: { paragraphs: textRef } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } label { display: block; } textarea { display: block; } .btn { display: block; margin-top: 15px; } </style>

views/home.vue

<template> <div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{titleList}}</h3> </div> <div class="panel-body"> <table class="table table-hover"> <thead> <tr> <th>Pavadinimas</th> <th>ID</th> <th>Sukūrta</th> <th></th> </tr> </thead> <tbody> <tr class="appsList" v-for="app in apps" v-on:click="goInner(app)"> <td>{{app.name}}</td> <td>{{app['.key']}}</td> <td>{{app.created}}</td> <td><span class="glyphicon glyphicon-trash iconClick" aria-hidden="true" v-on:click="removeApp(app)"></span></td> </tr> </tbody> </table> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{titleAdd}}</h3> </div> <div class="panel-body"> <form id="form" class="form-inline" v-on:submit.prevent="addApp"> <div class="form-group"> <label for="appTitle">Pavadinimas:</label> <input type="text" id="appTitle" class="form-control" v-model="newApp.name"> <input type="submit" class="btn btn-primary" value="Kurti"> </div> </form> </div> </div> </div> </template> <script> import Firebase from 'firebase' import firebaseconfig from '../firebase/config' import toastr from 'toastr' // Firebase Stuff let firebase = Firebase.initializeApp(firebaseconfig) let database = firebase.database() let appRef = database.ref('apps') export default { name: 'home', data () { return { titleMain: 'LiveText v1.0 for lrytas.lt', titleList: 'Aplikacijos', titleAdd: 'Sukurti naują aplikaciją', newApp: { name: '', created: this.getTime() } } }, methods: { getTime: function () { var date = new Date() var dateFormated = date.toLocaleDateString('lt') var timeFormated = date.toLocaleTimeString('lt', {hour12: false, hour: '2-digit', minute: '2-digit'}) var current = dateFormated + ' ' + timeFormated return current }, addApp: function () { appRef.push(this.newApp) this.newApp.name = '' toastr.success('Aplikacija sėkmingai sukurta!') }, removeApp: function (app) { appRef.child(app['.key']).remove() toastr.success('Aplikacija sėkmingai pašalinta!') }, say: function (id) { alert('Your app id is' + id) }, goInner: function (app) { this.$router.push({ name: 'inner', params: { appid: app['.key'], app: app } }) } }, firebase: { apps: appRef } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> label { display: block; } .btn { display: block; margin-top: 15px; width: 100%; } </style>

router/index.js

import Vue from 'vue' import Router from 'vue-router' import Home from '../views/Home' import Inner from '../views/Inner' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/app/:appid', name: 'inner', component: Inner } ] })
Categories: Software

Vue js not updating view with files data but able to console log

Wed, 2017-08-23 18:30

I am working on an image upload using vue.js but can't figure out this odd issue.

In my view:

{{ form.image }}

My data in the vue file:

data: function() { return { form: new SparkForm({ id: null, name: null, image: null }), imagePreview: null } },

And the method called when the file input is changed:

imageChanged: function(e) { var $this = this; let files = e.target.files || e.dataTransfer.file; if (!files.length) { return; } else { $this.form.image = files[0]; console.log($this.form.image); } },

This will console log the files information correctly, but in the view I just get an empty object.

Can't see anything obvious...

Categories: Software

Pages