Software
Eventbus in Vue.js isn't updating my component
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?
declare onended event in a child of vuejs template
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??
Float 1000.00 is smaller than 999.00, why is this? Vue Javascript [duplicate]
This question already has an answer here:
- Stuck on an If Statement in Javascript 2 answers
- Decimal comparison failing in JavaScript 1 answer
- Why is this else statement not triggered? 6 answers
I have 2 floats:
console.log(parseFloat(this.bid).toFixed(2)); console.log(parseFloat(this.highestBid.bid).toFixed(2));Output:
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?
Using custom components as router-link tag in Vue
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?
VueJs input previsualization, does not change my data inside FileReader listener
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
Tag <slot> cannot appear inside <table> due to HTML content restrictions. It will be hoisted out of <table> by the browser
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'">▲</span> <span v-else>▼</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
Momentjs used in Vue displays UTC time, but local time expected
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?
Submit a form in vue. How do I reference the form element?
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()?
router-link replace with vue-router?
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?
What vue.js hook do I need to use to validate an internal variable on page load?
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?
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 HOOKHow to remove the html element using $http.delete in VueJS
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); }); } } }JavaScript -- export default was not found
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?
npm run dev cant work,help!~
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~
How to validate specific data in an object(Vee-validate) and show custom error message
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: '' } }How to add dynamic/async/lazy components in VueJs
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 B3I 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.
VueJS Router doesn't load the component
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 :
and when I click the each nav, nothing is changed from the main page except URL. URL becomes
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.
how to use "v-for" for adding or removing a row with multiple components
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>Statement on U.S. DACA Program
We believe that the young people who would benefit from the Deferred Action for Childhood Arrivals (DACA) deserve the opportunity to take their full and rightful place in the U.S. The possible changes to the DACA that were recently reported would remove all benefits and force people out of the U.S. – that is simply unacceptable.
Removing DREAMers from classrooms, universities, internships and workforces threaten to put the very innovation that fuels our technology sector at risk. Just as we said with previous Executive Orders on Immigration, the freedom for ideas and innovation to flow across borders is something we strongly believe in as a tech company. More importantly it is something we know is necessary to fulfill our mission to protect and advance the internet as a global public resource that is open and accessible to all.
We can’t allow talent to be pushed out or forced into hiding. We also shouldn’t stand by and allow families to be torn apart. More importantly, as employers, industry leaders and Americans — we have a moral obligation to protect these children from ill-willed policies and practices. Our future depends on it.
We want DREAMers to continue contributing to this country’s future and we do not want people to live in fear. We urge the Administration to keep the DACA program intact. At the same time, we urge leaders in government to enact a bipartisan permanent solution, one that will allow these bright minds to prosper in the country we know and love.
The post Statement on U.S. DACA Program appeared first on The Mozilla Blog.
Getting a firebase object's key after it has been passed down as a prop in Vue
I am new to Firebase. I have a thought schema in the firebase database like this:
{ title: "I should learn VueJS + Firebase", body: "With VueJS+Firebase, I can take over the worlddd! Here's how I'll do it..." }Using the ListOfThoughts.vue component, we can render our thoughts to our template like this:
<template> <div class="list-of-thoughts"> <ThoughtItem v-for="thought in thoughts" :thought="thought" /> </div> </template> <script> import firebase from './../firebase' import ThoughtItem from './ThoughtItem.vue' export default { components: { ThoughtItem }, data () { return { thoughts: [] } }, created() { const thoughtsRef = firebase.database().ref().child('thoughts'); thoughtsRef.on('value', snapshot => { this.thoughts = snapshot.val(); }, errorObject => { console.log('Error retrieving thoughts: ' + errorObject.code); }) } } </script>Notice that we are using the ThoughtItem component which looks like this:
<template> <div class="thought"> <h1>{{thought.title}}</h1> <p>{{thought.body}}</p> </div> </template> <script> import firebase from './firebase' export default { props: ['thought'], methods: { getThoughtKey() { // How can we access the Key of this particular `thought` here? // I need the key value to access the database object. Like this: firebase.database().ref().child(key); } } } </script>(Please check out the comments)
I am hoping to access the Key of this thought object so that I may update it. How can I do this?
Javascript: (How) can you use filter to search in multiple key values of objects in an array?
I have an array of Wines containing an object with data for each wine:
var wines = [ { _id: '59a740b8aa06e549918b1fda', wineryName: 'Some Winery', wineName: 'Pinot Noir', wineColor: 'Red', imageLink: '/img/FortBerensPN.png' }, { _id: '59a7410aaa06e549918b1fdb', wineryName: 'Some Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a74125aa06e549918b1fdc', wineryName: 'Some Winery', wineName: 'Rose', wineColor: 'Rose', imageLink: '/img/FortBerensRose.png' }, { _id: '59a74159aa06e549918b1fdd', wineryName: 'Some other Winery', wineName: 'Rose', wineColor: 'Rose', imageLink: '/img/FortBerensRose.png' }, { _id: '59a7417aaa06e549918b1fde', wineryName: 'Some other Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a8721f4fd43b676a1f5f0d', wineryName: 'Some other Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a872244fd43b676a1f5f0e', wineryName: 'Winery 3', wineName: 'Pinot Noir', wineColor: 'Red', imageLink: '/img/FortBerensPN.png' } ]I can figure out how to search for a wine object while specifying which key of the object to search in like this: (need to use toLowerCase as var search will be user input)
var search = 'Noir' filteredWines = function () { return wines.filter(function(wine){ return (wine.wineName.toLowerCase().indexOf(search.toLowerCase())>=0 }) // returns: // [ { _id: '59a740b8aa06e549918b1fda', // wineryName: 'Some Winery', // wineName: 'Pinot Noir', // wineColor: 'Red', // imageLink: '/img/FortBerensPN.png' }, // { _id: '59a872244fd43b676a1f5f0e', // wineryName: 'Winery 3', // wineName: 'Pinot Noir', // wineColor: 'Red', // imageLink: '/img/FortBerensPN.png' } ]However, if var search = 'Winery 3' or var search = 'red' then it will obviously return no results as it's looking in the value of wineName of each object in the array.
So is there a way to use filter (or another method?) to search through all key values, or even better multiple specified key values and return an array of the matching objects?
Something like:
filteredWines = function () { return wines.filter(function(wine){ return ((wine.wineName.toLowerCase() && wine.wineName.toLowerCase() && wine.wineName.toLowerCase()).indexOf(search.toLowerCase())>=0 })Or am I completely barking up the wrong tree?!
PS. I'm using Vue.js 2 so if there's a better way inside vue then I'm all ears!
Thank you!