Vuejs

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

Array child in conditional rendering in vue.js

Mon, 2017-09-04 15:55

I have api on laravel and front on vue + laravel. I am getting all the data from api and pass it to view. Now I want to do conditional rendering.

My array looks like:

"data" => array:2 [▼ 0 => array:5 [▶] 1 => array:5 [▶]

I want to show div if topic from link is the same topic from array. But I do not know how to search and compare that words. So it will be like that:

v-if="$topic == this.topic"

But now I can only use

v-if="$data[]['0']['topic']"

and then I have the same topic on all my views.

My link looks like:

/user/{topic}/post

How to do it correctly guys?

Categories: Software

Why doesnt node express include my vue file?

Mon, 2017-09-04 15:40

So i have two script files that I am trying to include. one is a javascript file and the other a vue file.

the javascript file gets included but for some reason the vue file does not get included. I do not get any errors.

three structure:

enter image description here

hbs page:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> --> <link rel="stylesheet" type="text/css" href="/Static/css/spaceGame.css"> <!-- <link rel="stylesheet" href="css/normalize.css"> --> <link href="https://fonts.googleapis.com/css?family=Raleway:300,400" rel="stylesheet"> <title>{{title}}</title> </head> <body> {{{body}}} <!-- Footer --> <script src="https://unpkg.com/vue"></script> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="/Static/script/space.js"></script> <script type="text/javascript" src="/Static/script/someTest.js"></script> </body> </html>

script:

var express = require('express'); var hbs = require('express-handlebars'); var app = express(); var orgininPath = require("path"); var routes = require(orgininPath.resolve('./hoast/routerHandler/routes')); app.listen(3000, function() { console.log('Listening on port 3000'); }); app.use(express.static(orgininPath.join(orgininPath.resolve('./'), 'public'))); var url = require('url'); app.engine('hbs', hbs({ extname: 'hbs', defaultLayout: 'layout', layoutsDir: orgininPath.resolve('./Views/Layout/') })); app.set('view engine', 'hbs'); app.use('/', routes); module.exports = app;

Browser includes js file but now vue file:

enter image description here

What am I missing?

Categories: Software

Debugging UI Tests written with Testcafe

Mon, 2017-09-04 14:40

We are using Testcafe + Webpack + Vue.js for our project. I know that it is possible to debug the test code either by t.debug() directive or --inspect flag of node.js.

However, I can only see the production code (bundle.js) which is obfuscated and not really debuggable. I wonder if it is possible to have a configuration so that the testcafe does not use the bundled code but rather the original source code (probably with sourcemaps?). I am using source-map as the devtool option in webpack.

I am aware that the UI tests should test the production code but it would be nice to have such a configuration while developing. Any ideas?

Categories: Software

Vue get current component as a node?

Mon, 2017-09-04 14:10

I need to get the current position of a Vue component in the DOM. I know that I can get the HTMLElement of a component by using:

this.$el

This is not a node though. I need to be able to perform an appendChild on the current component so therefore I need a node.

Is there a proper way to do this?

Categories: Software

Passing a jquery variable to vue js

Mon, 2017-09-04 14:03

I have this code that posts some data to a remote server and receives the success message. I am getting an array and i am using that array to contain various pieces of data. I want to use a particular data to show if the direction of a trad is up or is down using vue js.

This is the jquery code

var email = window.localStorage.getItem("email"); var rid = window.localStorage.getItem("rid"); var ob = { 'email' : email, 'id' : rid }; var data = decodeURIComponent($.param(ob)); setInterval(function() { $.ajax({ url: 'http://example.world/mobile/index.php/welcome/my_trade_details', type: 'POST', data: data, success: function (data) { data = JSON.parse(data); $('#started_at').html(data.trade_start); $('#ended_at').html(data.trade_end); $('#my_trade_is').html(data.trade_direction); $('#result_is').html(data.trade_result); $('#trade_status').html(data.trade_status); $('#concurrency').html(data.trade_concurrency); $('#amount').html(data.trade_amount); $('#etherum_contract_number').html(data.etherum_contract_number); }, error: function (data, textStatus, jqXHR) { if(typeof data === 'object'){ var data = 'No Internet Connection Detected'; } } }); }, 5 * 1000);

and this is the vue js code

<div v-if="trade_direction === 'up'"> <i class="green material-icons">arrow_upward</i> </div> <div v-else> <i class="green material-icons">arrow_downward</i> </div>

How can i define and pass the variable trade_direction between jquery and vue js?.

Categories: Software

Vue/css - how to use :last-child selector when looping over items

Mon, 2017-09-04 14:02

I have articles array, through which I loop and create media objects for each of them. This is the parent component:

<div v-for="article of mostReadNews" class="most-read"> <media-object :article="article"></media-object> </div>

And this is the template of the media-object component:

<template> <router-link :to="article.link"> <article class="media"> <figure class="media-left"> <p class="image is-96x96"> <img :src="article.image.data.path"> </p> </figure> <div class="media-content"> <div class="content"> <h6 class="is-6">{{ article.title }}</h6> <span class="time-icon"><i class="material-icons">query_builder</i> {{ createdAt }}</span> </div> </div> </article> </router-link> </template>

The problem I have is that if I set with :last-child styling, like in my case, where I am setting the border-bottom for each element, except for the last one, it overwrites the first rule and none of the elements get border. I have tried with setting the css both in parent and child component, as well as in the theme.scss, but every time the border bottom of the last child selector overwrites the border bottom that I have set up for other items. This is the css:

<style scoped lang="scss"> @import "../assets/theme"; article { border-bottom: 1px solid $grey-lighter; } article:last-child { border-bottom:none; }

How can I fix that?

Categories: Software

Configure RouteConfig in vue.js

Mon, 2017-09-04 13:49

I use Vue.js 2.3, I want to define my own class for active href.

I saw 'linkActiveClass' option in the doc, but I can't figure out how to use it. I tried directly in code :

<router-link :to="{path : 'about', linkActiveClass: 'active', exact: true}" class="item" :linkActiveClass="active"><i class="icon talk"></i> About</router-link>

It doesn't work. I think I can define it in RouteConfig, but how to do that ? I see nothing in doc.

Categories: Software

BMap is not defined in Vue

Mon, 2017-09-04 13:29

I used two methods to call Baidu map

first

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=token"></script>

An external resource is set in webpack.base.conf.js

externals: { "BMap": "BMap"}

but

Uncaught ReferenceError: BMap is not defined

second

new baiduMap.js

export function MP(ak) { return new Promise(function (resolve, reject) { window.onload = function () { resolve(BMap) } var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://api.map.baidu.com/api?v=2.0&ak="+ak; script.onerror = reject; document.head.appendChild(script); }) }

import {MP} from './baiduMap.js'

mounted(){ this.$nextTick(function(){ var _this = this; MP(_this.ak).then(BMap => { }}

The second method can be loaded Baidu map,but on the second page,map not loaded again。

How can i do?

Categories: Software

How to restart data() on route with no params

Mon, 2017-09-04 13:15

I have a problem to force a restart on new route

I have an route

/editor but also /editor?_id=dasd448846acsca

/editor is simple component with form with empty inputs /editor?_id=dasd448846acsca this component is the same as /editor but just with filled inputs from DB I want to be able to open /editor component (using some function, link) with empty inputs from component /editor?_id=dasd448846acsca

I used this.$router.push('editor'); this.$forceUpdate(); in function and route is changed, but data in restarted (inputs are not empty)

Categories: Software

Why need Vuex, Flux or Redux when we have websocket technology?

Mon, 2017-09-04 12:37

Why do we need Vuex, Flux, Redux and The Elm Architecture when we can achieve the same result with websocket? What I need to do to make sure each component sharing the same data.

For instance (Nuxt.js + Socket.io):

<template> <div> // Component 1 <span> <ul id="messages"> <li v-for="message in messages">{{message}}</li> </ul> </span> // Component 2 <span> <ul id="messages"> <li v-for="message in messages">{{message}}</li> </ul> </span> <!-- the submit event will no longer reload the page --> <form v-on:submit.prevent="submitMessage"> <input id="m" autocomplete="off" v-model="inputMessage"/> <button type="submit">Send</button> </form> </div> </template> <script> import axios from '~/plugins/axios' import socket from '~/plugins/socket.io' socket.on('news', function (data) { console.log('server message received: ' + data) socket.emit('my other event', { my: 'data' }) }) export default { layout: 'dark', // you can set a custom layout here. async asyncData () { let data = await axios.get('/api/tasks') console.log(data.data) return { inputMessage: '', messages: ['hello'] } }, head () { return { title: 'Users' } }, created () { socket.on('chat.message', function(data) { this.messages.push(data) }.bind(this)) }, methods: { submitMessage() { socket.emit('chat.message', this.inputMessage) this.inputMessage = '' } } } </script>

This seems a lot easier, simpler and interesting as it is a real-time update.

Any thoughts?

Categories: Software

Checking for watch changes after data is set on mounted

Mon, 2017-09-04 11:55

i am trying to edit a component, when i open the component i load his data with mounted like this:

mounted () { var sectionKey = this.$store.getters.getCurrentEditionKey this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey]) this.table.tableGrid = _.clone(this.$store.getters.getDocumentAttributes[sectionKey].tableGrid) this.entered = true },

as you guys can see i change the this.entered, i tried to track when the elements are loaded so i can start tracking with the watcher the changes on my component.

watch: { 'table.rows': function (val, oldValue) { if (this.entered === true) { if (val > oldValue) { this.table.tableGrid.push(['']) } else if (val < oldValue) { this.table.tableGrid.splice(this.table.tableGrid.length - 1, 1) } } }, 'table.cols': function (val, oldValue) { if (this.entered === true) { if (val > oldValue) { for (var i = 0; i < this.table.rows; i++) { this.table.tableGrid[i].push('') } } else if (val < oldValue) { for (var j = 0; j < this.table.rows; j++) { this.table.tableGrid[j].splice(this.table.tableGrid[j].length - 1, 1) } } } }

i am tracking my table cols and table row, it is a number input that i change if i want, the problem is that it enters the watcher before the mounted, i don't know how can i handle this situation any help?

Categories: Software

Why updated not working on vue.js?

Mon, 2017-09-04 10:37

My code like this :

updated() { console.log('test') },

Demo and full code like this : https://jsfiddle.net/50wL7mdz/58492/

I check on console, the result of console.log('test') not display

If I use mounted, it works

Why if I use updated, it does not work?

How can I solve the problem?

Categories: Software

Vue js computed properties evaluation order

Mon, 2017-09-04 10:31

I have a component which uses 'data1' props.

<template> <div> <component1 :data='data1'><component1> </div> <template>

This data1 is a computed property which needs another computed data for calculating one of its values:

computed: { componentInfo: function() { return this.$store.state.componentData; } data1: function() { return {value1: this.componentInfo.value1, ... other values} } }

My problem is that the component tries to evaluate data1 value before getting the componentInfo from the store (which causes an error since this.componentInfo is still undefined)

How should such a scenario be treated?

Categories: Software

How to custom v-for using v-if for make a class in div tag

Mon, 2017-09-04 10:18

How to correctly way use v-if when I using v-for inside?

Actually I want to add a condition when the index is 0 or first data is displayed I want to add active class

<div class="item active" v-for="(item, key, index) in slideItem" :key="item._id"> <img alt="900x500" src="http://lorempixel.com/960/720/"> <div class="carousel-caption"> <h3>{{ item.title }}</h3> <p>{{ item.body }}</p> </div> </div>

and show this when the next data :

<div class="item" v-for="(item, key, index) in slideItem" :key="item._id"> <img alt="900x500" src="http://lorempixel.com/960/720/"> <div class="carousel-caption"> <h3>{{ item.title }}</h3> <p>{{ item.body }}</p> </div> </div>

You can see the two examples I gave, how I combine the two loops into one by distinguishing the first index (item active) condition and so on using v-if

Categories: Software

How to put content under certain headings

Mon, 2017-09-04 06:35

How to put content under certain headings? I have two methods to load data

first axios.get('/api/get/headers')

second axios.get('api/get/contents')

I have no idea how correctly this will be done, given that the headers can be different and the content is correspondingly too

Categories: Software

Axios not working on Android after Phonegap Build

Mon, 2017-09-04 04:23

I've got a problem in my Phonegap .apk after build it on their site, my problem is axios not working, but in my Desktop Phonegap App it works fine. I don't know what is/are the issue(s) that I have encounter, is this because of my axios?

Technologies: Axios , VueJS , Phonegap

Here's my index.js look like:

Vue.directive('focus', { inserted: function(el) { return el.focus(); } }); var apiURL = 'http://stishs-grade-and-progress-report-monitoring-system.cf/', tokenString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; var Authentication = Vue.component('sti-main', { data() { return { username: '', password: '', error: { flag: false, message: '' } } }, template: ` <main> <form class="sti-form-auth" v-on:submit.prevent="signInProceed(username, password)"> <div class="sti-logo"> <img src="img/sti-logo-250.png" alt="STI Grading and Progress Report Monitoring System Logo"> </div> <h1 class="sti-form-title">STI Grading and Progress Report Monitoring System</h1> <div class="sti-addon sti-form-control"> <input type="text" class="sti-block" placeholder="Username" v-on:keydown="hideNotif" v-model.trim="username" v-focus ref="Username"> <i class="ion ion-android-person"></i> </div> <div class="sti-addon sti-form-control"> <input type="password" class="sti-block" placeholder="Password" v-on:keydown="hideNotif" v-model.trim="password" ref="Password"> <i class="ion ion-android-lock"></i> </div> <div class="sti-form-control"> <button class="sti-block sti-button-blue">Sign in</button> </div> </form> <div v-show="error.flag" class="sti-error-message"> <p class="sti-error-title"><i class="ion ion-alert-circled sti-right-5"></i>Error Found!</p> <p>{{ error.message }}</p> </div> <div class="sti-footer-auth"> <p class="sti-center">Copyright &copy; 2017 STI Grading and Progress Report Monitoring System. All Rights Reserved.</p> </div> </main> `, created: function() { var authToken = localStorage.getItem('stishTokenAPI') if(authToken != null && authToken.split('&')[2] == 3) { var authData = `method=check&0=${authToken.split('&')[0]}&1=${authToken.split('&')[1]}` return axios.post(`${apiURL}sti-api/authentication.php`, authData).then(function(response) { var authenticated = response.data if(authenticated.count == 1 && authenticated.type_id == 3) { return window.location.href = './student.html' } return window.location.href = './index.html' }); } }, methods: { hideNotif: function() { return this.error.flag ? this.error.flag = false : true }, generateToken: function(generateToken = '') { for(var i = 0; i < tokenString.length; i++) { generateToken += tokenString[Math.floor(Math.random() * (tokenString.length - 1)) + 1]; } return generateToken; }, signInProceed: function(user, pass) { var vm = this if(user == '' || pass == '') { var errorType = user == '' ? 'Username' : 'Password' vm.$refs[errorType].focus() vm.error.message = `- Missing credential. ${errorType} is required!.` vm.error.flag = true return } var authToken = vm.generateToken() var parameter = `method=auth&username=${vm.username}&password=${vm.password}&token=${authToken}` return axios.post(`${apiURL}sti-api/authentication.php`, parameter).then(function(response) { var account = response.data if(account.success && account.details.type_id == 3) { localStorage.setItem('stishTokenAPI', `${authToken}&${account.details.account_id}&${account.details.type_id}`) return window.location.href = './student.html' } vm.error.message = `- ${account.message}` return vm.error.flag = true }); } } }); new Vue({ el: '#auth' });

Here's my index.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>STI Grading and Progress Report Monitoring System</title> <link rel=stylesheet href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto+Mono|Source+Sans+Pro:300,400,500,600"> <link rel="stylesheet" href="css/app.css"> </head> <body> <main id="auth"> <sti-main></sti-main> </main> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/axios.min.js"></script> <script type="text/javascript" src="js/vue.min.js"></script> <script type="text/javascript" src="js/index.js"></script> </body> </html>

Categories: Software

Duplicate registration of components in Vue.js

Mon, 2017-09-04 04:22

If i had a repository which held all of my Vue components, and a system by which my other codebases could pull in the components they required from this Vue repo.

I have 2 components, 1 of which is used as a child in the other but can also be used in a standalone fashion. Because I'd like for there to be minimal implementation knowledge needed for the use of these components, I'd like to import the child in the parents script as such

<template> <child-component></child-component> </template> <script> import childComponent from 'path/to/child/child-component.vue' export default { name: 'parent-component', components: { 'child-component': childComponent } } </script>

Doing this will register the child-component in the parent's scope and it can't be used outside of that scope. So if I need to now use child-component as a standalone component I'll also need to register it in the global scope in the base JS file, where I'm importing vue components into as such:

import Vue from 'vue'; import childComponent from 'path/to/child/child-component.vue'; import parentComponent from 'path/to/parent/parent-component.vue'; function registerComponents() { Vue.component(childComponent.name, childComponent); Vue.component(parentComponent.name, parentComponent); } function initVue() { registerComponents(); new Vue({ el: '#vue-app' }); } window.addEventListener('load', initVue);

My question is thus, if I were to register childComponent with parentComponent and then again with the global scope, is Vue smart enough to sort this out or will my compiled JS have the code duplicated.

If the code is in fact duplicated and childComponent was listening for events, what would happen if the event occurred?

Categories: Software

how to set the data object in a vue-resource such that it won't error in console

Mon, 2017-09-04 01:19

I am learning Vue this weekend so a very simple question.

I'm trying to convert some jQuery to using Vue with vue-respource. I am getting back data for a location with items. The problem I'm having is that whenever I load this object, I get an error saying the location is null (which is what I set it to be in data. What is the proper way to do this? Should I have a guard statement to prevent it rendering through items? If it was an array of locations, I could set to an empty array but for a single object, it seems like should be null. How best to have an empty data object that is filled via an async call?

const Location = { data(){ return {location: null } }, template: `<div>{{location.name}} <div v-for="item in location.items"> <div>{{item.id}}</div> </div> </div>`, created(){ this.fetchData(); }, methods: { fetchData(){ this.$http.get('/arc/api/v1/site_admin/locations/' + this.$route.params.id + '/dashboard').then((response) => { console.log(response.data); this.location = response.data.location }).catch( error => { console.log(error); }); } } }
Categories: Software

Rails Webpacker Vue '__webpack_require__(...) is not a function' Error

Sun, 2017-09-03 23:26

I'm getting this error after I run '/bin/webpack-dev-server' and make any changes to .vue files. When I first run the server everything works fine, it's only after I make changes that this error gets thrown. On a side note changes to the hello_vue.js file do not flash this error and they do show.

The files gets recompiled successfully in the system terminal too when the dev-server is running. I've added nothing out of the ordinary to the application as this is a new project.

The guide at https://github.com/rails/webpacker was used to get webpacker up and running.

Could this be a turbolinks error?

Any help is appreciated!

hello_vue.js

import Vue from 'vue/dist/vue.esm' import App from './app.vue' document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#hello', data: { message: "Can you say hello?" }, components: { App } }) })

app.vue

<template> <div id="app"> <center> <p>{{ message }}</p> <button type="button" name="button" @click="addOne">Click me!</button> <p>This is a number test: {{ data }}</p> </center> </div> </template> <script> export default { data: function () { return { message: "Hello Vue! From inside app.vue!", data: 5 } }, methods: { addOne(){ this.data += 1 console.log(this.data) } } } </script> <style scoped> p { font-size: 2em; text-align: center; } </style>

package.json

{ "dependencies": { "@rails/webpacker": "^3.0.0", "vue": "^2.4.2", "vue-loader": "^13.0.4", "vue-template-compiler": "^2.4.2" }, "devDependencies": { "webpack-dev-server": "^2.7.1" } }

consoler debugger:

exports = module.exports = require("../../../node_modules/css-loader/lib/css-base.js")(undefined); // imports // module exports.push([module.id, "\np[data-v-13f0f5d2] {\n font-size: 2em;\n text-align: center;\n}\n", ""]); // exports ////////////////// // WEBPACK FOOTER // ./node_modules/css-loader!./node_modules/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-13f0f5d2","scoped":true,"hasInlineConfig":false}!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./app/javascript/packs/app.vue // module id = 0 // module chunks = 0

browser console:

<anonymous> webpack-internal:///0:1:28 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:75:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///47:5:16 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:628:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///46:5:3 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:616:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///45:3:21 <anonymous> webpack-internal:///45:1:29 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:604:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///44:1:14 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:592:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///34:5:14 <anonymous> webpack-internal:///34:1:29 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:475:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:1209:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:63:18 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:1:11
Categories: Software

How to pass changed value to other component's methods in Vue.js?

Sun, 2017-09-03 21:03

In the header component, let's call it App.vue, there is a select element:

<select v-model="locale"> <option value="en">English</option> <option value="pl">Polski</option> </select>

In the same component, the option selected by user gets processed in watch:

watch: { locale (val) { this.$i18n.locale = val; console.log("locale: ", val); localStorage.setItem("userPrefLang", val); } },

How can I notify other components (siblings, not children), let's say Users.vue, that the locale parameter was changed? I'd like to pick up the new value in the code (using a JS method), not with bound DOM elements. The new value should trigger the page reload due to changed locales. Should I use Users.vue's watcher, props, or is there any other way?

Categories: Software

Pages