Vuejs

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

Listen to events from parent component in child and execute child’s method in vue without hub

Fri, 2017-09-01 14:37

There seems to be a lot of discussion around this topic such as Stackoverflow answer using hub, Stackoverflow answer using refs, so I really like to ask experts to provide for once a clear concise answer to this question. If the answer is also just not possible please state that!

Here is the scenario: There are two components, a parent and a child

<Parent> // There is a button here that can be clicked to emit an event using 'this.$emit()' <Child></Child> // The child listens and once hears the event, it does something </Parent> What to be achieved?

Clicking the button in the Parent emits a certain event, the child will be constantly listening and once it hears the event it executes an action, such as calling a method of its own.

What is out there about this so far?
  1. Using a hub, in Vue Hub it is clearly stated this is for Non Parent-Child Communication, so what is the point in using it for a parent-child communication?

  2. Using Refs, which is given as an end solution when it is not possible to use props and events. So why it is not possible with events at first place?

My own thought

It seems to me the firing of an event and listening to it is only possible from child to parent, basically one way communication. The parent is able to emit an event but child component(s) are not able to capture the event. Why? I tried this and didn’t work:

In the parent component I have (triggered by clicking a button in the parent component):

methods: { generateCharts: function () { this.$emit('generate-charts') console.log('charts generated') }

In the child component I have:

mounted () { this.parent.$on('generate-charts', function () { console.log('event captured') // Here nothing gets logged to the console }) }
Categories: Software

How to access the getter from another vuex module?

Fri, 2017-09-01 13:47

Within a vuex getter I know it is possible to access the state from another vuex module like so:

pages: (state, getters, rootState) => { console.log(rootState); }

How can I access a getter from another vuex module instead of the state though?

I have another vuex module called filters that I need to access, I have tried this:

rootState.filters.activeFilters

Where activeFilters is my getter but this does not work. using rootState.filters.getters.activeFilters also does not work.

Categories: Software

How to send data from web to api?

Fri, 2017-09-01 12:47

Sorry for question but I don't understand that.

I have this:

<a @click.prevent="Submit(0)" href="#">NO</a> <a @click.prevent="Submit(1)" href="#">OK</a>

Now in my vue method submit I want to post value 0 or 1 to my api and then store it in database. I have controller UserVote and model Vote. I am green here.

I must send it like this:

submit(value){ this.$http.post('/user/vote', JSON.stringify(WHAT HERE?)).then(response => { toastr.success(response.body.data[0]); if(response.body.redirect) { window.location.href = response.body.redirect; } }, response => { if(response.status == 422) { opinion = response.body.data; } else if(response.status == 401) { toastr.error(response.body.data.message); } }); }

How my link should do? Where I post that? How I can upload that to db? I need just know, then I will be know everything.

Categories: Software

Eventbus in Vue.js isn't updating my component

Fri, 2017-09-01 12:35

I have two components and I want to display what the user enters in one on the other component. I don't really want to use a state manager like vuex because it's probably a bit overkill as it's a small application

this is my main.js:

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

Component that emits the event called addHtml.vue

<template> <div> <h1>Add HTML</h1> <hr> <button @click="navigateToHome" class="btn btn-primary">Go to Library</button> <hr> Title <input type="text" v-model="title"> <button @click="emitGlobalClickEvent()">Press me</button> </div> </template> <script> import { EventBus } from '../../main.js' export default { data: function () { return { title: '' } }, methods: { navigateToHome() { this.$router.push('/'); }, emitGlobalClickEvent() { console.log(this.title); EventBus.$emit('titleChanged', this.title); } } } </script>

the file that listens for the event thats emitted and to display what was entered on the other component:

<template> <div> <h1>Existing Items</h1> <hr> <p>{{ test }}</p> </div> </template> <script> import { EventBus } from '../main.js'; export default { data: function () { return { test: '' } }, created() { EventBus.$on('titleChanged', (data) => { console.log('in here!',data); this.test = data; }); } } </script>

the console.log('in here!',data); inside the listener gets printed out to the console so I know it's picking it up however {{ test }} doesn't get updated to what the user enters when I click back onto the component to view if it was updated, it just remains blank? Any Ideas?

Categories: Software

declare onended event in a child of vuejs template

Fri, 2017-09-01 12:20

In my template of a custom music player I have a html5 tag child, is what play music, and I want to request next song after end, I think that put all the onended event inside the templete isn't a good practice and I want how to make this correctly.

Here it is the template:

<template> <footer id="player" class="player"> <progress min="0" max="1" value="0" ref="progress"></progress> <div class="div-player"> <i class="material-icons play-button player-button" >skip_previous</i> <i class="material-icons play-button player-button" v-on:click="togglePause">play_circle_outline</i> <i class="material-icons play-button player-button" >skip_next</i> <audio ref="audioTag" :src="source" autoplay preload="none" @timeupdate="onTimeUpdateListener"></audio> <a class=".primary-text-color" style="text-align: center; font-size: small;">{{ title }}</a> </div> <!-- <progress min="0" max="1" value="0" ref="progress"></progress> --> </footer> </template>

I started by putting the listener into the component logic but wasn't work. Any help with this??

Categories: Software

Float 1000.00 is smaller than 999.00, why is this? Vue Javascript [duplicate]

Fri, 2017-09-01 12:10

This question already has an answer here:

I have 2 floats:

console.log(parseFloat(this.bid).toFixed(2)); console.log(parseFloat(this.highestBid.bid).toFixed(2));

Output:

enter image description here

if(parseFloat(this.bid).toFixed(2) <= parseFloat(this.highestBid.bid).toFixed(2)) { // triggers this }

Why is this If statement triggering? 1000.00 is clearly larger than 999.50...

This only happens when this.bid gets 1000 or larger.

if this.bid is 999.51 it works perfectly.

Why is this happening?

Categories: Software

Using custom components as router-link tag in Vue

Fri, 2017-09-01 11:50

I'm trying to make the following Vue component work:

<template> <div> <cx-button href="/new"> Create </cx-button> <router-link tag="cx-button" to="/new" class="cx-raised">Create</router-link> </div> </template> <script> import cxButton from '../elements/cxButton/cxButton'; export default { // ... components: { cxButton } } </script>

But it throws: [Vue warn]: Unknown custom element: <cx-button> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found in ---> <RouterLink>.

Name of the button element is provided.

cx-button component is rendered fine by itself, same for router-link without using cx-button as value in tag property. The question is: what should I do to make router-link use custom elements, such as my button, as its tag?

Categories: Software

VueJs input previsualization, does not change my data inside FileReader listener

Fri, 2017-09-01 11:23

I'm new to VueJs and currently designing a image picker component. I'm struggling with the file uploaded event, as my mutable properties doesn't want to update inside the event listener.

There's a part of the template code:

<input @change="handleUpload" type="file" :name="imageName" /> <img :src="mutableImageString" alt="Image" class="img-responsive" />

And the logic :

handleUpload: function (e) { var reader = new FileReader(); var file = e.target.files[0]; reader.onload = function () { this.mutableImageString = file; } if (file) { reader.readAsDataURL(file); } },

mutableImageString isn't updated, however if I take it out of the onload event, it's updated but with an empty value. Any idea? Thanks!

PS: Sorry about my poor english :c

Categories: Software

Tag <slot> cannot appear inside <table> due to HTML content restrictions. It will be hoisted out of <table> by the browser

Fri, 2017-09-01 11:19

I am new to vuejs, While running the following code I am getting the error mentioned at the bottom. Please suggest what should I change.

<template> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-striped"> <thead> <tr> <th v-for="item in thead"> <div class="dataviewer-th" @click="sort(item.key)" v-if="item.sort"> <span>{{item.title}}</span> <span v-if="params.column === item.key"> <span v-if="params.direction === 'asc'">&#x25B2;</span> <span v-else>&#x25BC;</span> </span> </div> <div v-else> <span>{{item.title}}</span> </div> </th> </tr> </thead> <tbody> ----52----- <slot v-for="item in model.data" :item="item"></slot> </tbody> </table> </div> <div class="panel-footer pagination-footer"> <div class="pagination-item"> <span>Per page: </span> <select v-model="params.per_page" @change="fetchData"> <option>10</option> <option>25</option> <option>50</option> </select> </div> </div> </div> </template> <script> //some code </script>

While running the above code I am getting the following error

ERROR in ./resources/assets/js/components/valuechain/DataViewer.vue 51 | <tbody> 52 | <slot v-for="item in model.data" :item="item"></slot> | ^ 53 | </tbody>

Tag cannot appear inside due to HTML content restrictions. It will be hoisted out of by the browser

Categories: Software

Momentjs used in Vue displays UTC time, but local time expected

Fri, 2017-09-01 11:11

The momentjs documentation says: 'By default, moment parses and displays in local time.' (https://momentjs.com/docs/#/parsing/utc/).

If I display the output of moment() directly via javascript, thats indeed the case:

<div id="divLocal"> </div> document.getElementById("divLocal").innerHTML = moment();

Output: Fri Sep 01 2017 10:56:45 GMT+0200

If I do the same using Vuejs, it shows UTC time:

<div id='app'> <span>{{datenow}}</span> </div> new Vue({ el: '#app', data: { datenow: '' }, methods: { time() { var self = this; this.datenow = moment(); }, }, mounted: function() { this.time(); } });

Output: 2017-09-01T09:02:38.169Z

Example: https://jsfiddle.net/nv00k80c/1/

Someone has an idea why this is happening? If I use moment().format() in Vue, the output is also correct. But I wonder where and why there is a difference?

Categories: Software

Submit a form in vue. How do I reference the form element?

Fri, 2017-09-01 11:00

I want to do a classic form submission from my Vue page, from a method. I don't want to use an input type=submit. How do I reference the form element in the page from my method? Surely I don't have to do document.getElementById()?

Categories: Software

router-link replace with vue-router?

Fri, 2017-09-01 10:37

With the router-link tag with vue-router, "Setting replace prop will call router.replace() instead of router.push() when clicked, so the navigation will not leave a history record", according to the docs. But this doesn't seem to be happening for me, so I think I must be misunderstanding something. I have a navigation menu in my SPA and the router-link in each menu item has a replace prop. Yet when I click on each menu item in turn, it clearly does add to the history, in that the back button takes me back to the previous item, and I can actually see in the Firefox history the list of URLs being added to. What am I doing wrong?

Categories: Software

What vue.js hook do I need to use to validate an internal variable on page load?

Fri, 2017-09-01 10:17

I want to display an error message if necessary when a page loads. The only way I can get this to work is to call the validation method from outside the Vue instance.

Is there an internal hook that I could be using instead?

http://jsfiddle.net/edwardtanguay/ahd34a3v

HTML: <div id="app"> <input v-model="startTime" v-on:keyup="validateTime(startTime)"/> <div> {{errorMessage}} </div> </div> JavaScript: var vm = new Vue({ el: '#app', data: function() { return { startTime: 'hello', errorMessage: '' } }, mounted: function() { this.validateTime(startTime); }, methods: { validateTime: function(time) { this.errorMessage = 'the length is ' + time.length; } } }); // vm.validateTime(vm.startTime); //WORKS BUT IS NOT IN AN INTERNAL HOOK
Categories: Software

How to remove the html element using $http.delete in VueJS

Fri, 2017-09-01 10:08

I use $http.delete in a VueJS project to remove the users from a page. When I click on delete icon the user is delete it from the database but on the front end the html for that user is still on page. Will disappear if I refresh the page.

This whole HTML(down) is a user from a list of users, from a database. I tried wrapping the whole HTML with another div and use inside a v-if directive, but in this case will not show me any user.

So how can I remove the html element too, when I delete the user, without refreshing the page?

If there is another way to delete a user from database, beside this $http.delete, fell free to show it to me.

HTML

<template> <div> <div class="card visitor-wrapper"> <div class="row"> <div class="col-md-2"> <div class="checkbox checkbox-success"> <input type="checkbox" id="select-1"> <label for="select-1" style="width: 50px;"><img src="../../assets/icons/visitors-icon.svg" alt=""></label> </div> <i class="fa fa-user-o fa-2x" aria-hidden="true"></i> </div> <div class="col-md-3"> <p class="visitor-name">{{user.firstName}}</p> <span class="visitor-email">{{user.userType}}</span> </div> <div class="col-md-2"> <p class="visitor-other-detail">{{user.rid}}</p> </div> <div class="col-md-2"> <p class="visitor-other-detail">{{user.departmentId}}</p> </div> <div class="col-md-2"> <p class="visitor-other-detail">{{createdDate(user.createdDate)}}</p> </div> <div class="col-md-1 divider-left"> <div class="edit-icon"> <router-link :to="'/users/edit-user/'+user.rid"><a data-toggle="tooltip" data-placement="top" title="Edit Employee"><i class="ti-pencil-alt" aria-hidden="true"></i></a></router-link> </div> <div class="trash-icon"> <a data-toggle="tooltip" data-placement="top" title="Delete Employee" @click="removeUser(user.rid)"><i class="ti-trash" aria-hidden="true"></i></a> </div> </div> </div> </div> </div> </template>

JS

export default { props: ['user'], methods: { removeUser(item) { this.$http.delete('/user/' + item) .then((response) => { console.log('response', response); }); } } }
Categories: Software

JavaScript -- export default was not found

Fri, 2017-09-01 09:19

I have a Vue 2 project, and I've written a simple function for translating months in dates, which I would like to import in one of my components, but I'm getting an error:

export 'default' (imported as 'translateDate') was not found in '@/utils/date-translation'

The relative file path from the src folder is correct, and I am exporting the function like this:

export function translateDate(date) { // my code }

And then I am importing it in the component like this:

import translateDate from '@/utils/date-translation'

What am I doing wrong?

Categories: Software

npm run dev cant work,help!~

Fri, 2017-09-01 08:34

it's about vuejs project,i have try my best to resolve it when i run "npm run dev",but it cant work finaly =.=!!, i dont know why this happen,my system is win7 64bit,i have reinstall nodejs & npm and try many editions,but it dosent work,this is log below:

0 info it worked if it ends with ok 1 verbose cli [ 'D:\\nodejs\\node.exe', 1 verbose cli 'D:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'dev' ] 2 info using npm@5.3.0 3 info using node@v8.4.0 4 verbose run-script [ 'predev', 'dev', 'postdev' ] 5 info lifecycle vuedemo@1.0.0~predev: vuedemo@1.0.0 6 info lifecycle vuedemo@1.0.0~dev: vuedemo@1.0.0 7 verbose lifecycle vuedemo@1.0.0~dev: unsafe-perm in lifecycle true 8 verbose lifecycle vuedemo@1.0.0~dev: PATH: D:\nodejs\node_modules\npm\bin\node-gyp-bin;D:\vuedemo\node_modules\.bin;D:\cmder\bin;D:\cmder\vendor\git-for-windows\cmd;D:\cmder\vendor\conemu-maximus5\ConEmu\Scripts;D:\cmder\vendor\conemu-maximus5;D:\cmder\vendor\conemu-maximus5\ConEmu;D:\svn\bin;D:\MongoDB\bin;D:\cmder;D:\nodejs\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\xw\AppData\Roaming\npm;D:\cmder\vendor\git-for-windows\usr\bin;D:\cmder\vendor\git-for-windows\usr\share\vim\vim74;D:\cmder\ 9 verbose lifecycle vuedemo@1.0.0~dev: CWD: D:\vuedemo 10 silly lifecycle vuedemo@1.0.0~dev: Args: [ '/d /s /c', 'node build/dev-server.js' ] 11 info lifecycle vuedemo@1.0.0~dev: Failed to exec dev script 12 verbose stack Error: vuedemo@1.0.0 dev: `node build/dev-server.js` 12 verbose stack spawn ;d:\Git\cmd ENOENT 12 verbose stack at _errnoException (util.js:1041:11) 12 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19) 12 verbose stack at onErrorNT (internal/child_process.js:374:16) 12 verbose stack at _combinedTickCallback (internal/process/next_tick.js:138:11) 12 verbose stack at process._tickCallback (internal/process/next_tick.js:180:9) 13 verbose pkgid vuedemo@1.0.0 14 verbose cwd D:\vuedemo 15 verbose Windows_NT 6.1.7601 16 verbose argv "D:\\nodejs\\node.exe" "D:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev" 17 verbose node v8.4.0 18 verbose npm v5.3.0 19 error file ;d:\Git\cmd 20 error path ;d:\Git\cmd 21 error code ELIFECYCLE 22 error errno ENOENT 23 error syscall spawn ;d:\Git\cmd 24 error vuedemo@1.0.0 dev: `node build/dev-server.js` 24 error spawn ;d:\Git\cmd ENOENT 25 error Failed at the vuedemo@1.0.0 dev script. 25 error This is probably not a problem with npm. There is likely additional logging output above. 26 verbose exit [ 1, true ]

and command window msg below:

> vuedemo@1.0.0 dev D:\vuedemo > node build/dev-server.js npm ERR! file ;d:\Git\cmd npm ERR! path ;d:\Git\cmd npm ERR! code ELIFECYCLE npm ERR! errno ENOENT npm ERR! syscall spawn ;d:\Git\cmd npm ERR! vuedemo@1.0.0 dev: `node build/dev-server.js` npm ERR! spawn ;d:\Git\cmd ENOENT npm ERR! npm ERR! Failed at the vuedemo@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! code ELIFECYCLE npm ERR! errno -4058 npm ERR! vuedemo@1.0.0 dev: `node build/dev-server.js` npm ERR! Exit status -4058 npm ERR! npm ERR! Failed at the vuedemo@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

can anyone help me? thx a lot~

Categories: Software

How to validate specific data in an object(Vee-validate) and show custom error message

Fri, 2017-09-01 08:31

Hey guys how to validate specific data in an object in vee-validate. I just want to validate first name and last name in an object then show custom error message becease I'm using naming convention.

I want to validate first and last name when clicking submit

data() { return { per: { strFirst: '', strMiddle: '', strLast: '' } }

Here's my code

Categories: Software

How to add dynamic/async/lazy components in VueJs

Fri, 2017-09-01 07:20

I want to add child components in parent components on the fly based on some conditions. I have come up with following pseudo-code

If currentView == 'a' load component A1 load component A2 ElseIf currentView == 'b' load component B2 load component B3

I know we can register all components in parent component like:

Vue.component('a1-component', require('./A1Component.vue')); Vue.component('a2-component', require('./A2Component.vue'));

But I have a lot of such child components and I need to load only the required components when needed. So loading all components initially is an overhead.

I have tried Dynamic components and async-components in Vue Js. All Dynamic components are loaded altogether so its not what I want. I am not sure how Async components can be utilized to achieve this.

I am using Laravel 5.4, VueJs 2.3.3 and Webpack.

Categories: Software

VueJS Router doesn't load the component

Fri, 2017-09-01 05:31

I am using VueJS Router, but the router is not loading the components.

I have About.vue and Contact.vue just with tag to test - following is how it looks like :

<template> <div> <h1>Contact page. Welcome baby!</h1> </div> </template>

This is App.vue with three router-links and router-view.

<template> <div> <h1>Routing</h1> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> <router-link to="/contact">Contact</router-link> <router-view></router-view> </div> </template>

This is main.js (the paths of importing files are correct)

import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import {routers} from './router' Vue.use(VueRouter); let router = new VueRouter({mode: 'history', routers}); new Vue({ el:'#app', router, components: { 'app-home' : App } });

This is the JS file for the router. router.js (paths are correct)

import About from './About.vue' import Contact from './Contact.vue' import Home from './App.vue' export const routers=[ { path: '/' , component: Home }, { path:'/about',component:About }, { path:'/contact',component:Contact } ]

And, this is index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>router</title> </head> <body> <div id="app"> <app-home></app-home> </div> <script src="/dist/build.js"></script> </body> </html>

When I load the page, the main page looks like the following : Loaded Main page

and when I click the each nav, nothing is changed from the main page except URL. URL becomes

http://localhost:8080/contact

http://localhost:8080/about

but not loading the component I imported.

If you need more information to give advice, feel free to ask more. And if you have any clue of this issue, I appreciate if you share here.

Thank you.

Categories: Software

how to use "v-for" for adding or removing a row with multiple components

Fri, 2017-09-01 04:51

i have a row with 3 components(in which is a defined component 1, component 2 and component 3, as showed in my previous question: VueJs component undefined )

how can i add a row or remove a row (in which has 3 components) using v-for?

var data1={selected: null, items:["A", "B"]}; Vue.component('comp1', { template: `<select v-model="selected"> <option disabled value="">Please select</option> <option v-for="item in items" :value="item">{{item}}</option> </select>`, data:function(){ return data1 } }); <!---similar for component 2 and 3---> new Vue({ el: '#app', data: { rows:[] }, methods:{ addRow: function(){ this.rows.push({}); }, removeRow: function(row){ //console.log(row); this.rows.$remove(row); } }, });

in .html

<script src="https://unpkg.com/vue"></script> <div id="app"> <div v-for ="row in rows"> <comp1></comp1> <comp2></comp2> <comp3></comp3> <button @click="addRow">Add Row</button> <button @click="removeRow(row)">Remove Row</button> </div> </div>
Categories: Software

Pages