Software

BMap is not defined in Vue

Vuejs - 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

Vuejs - 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?

Vuejs - 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

Vuejs - 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?

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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?

Vuejs - 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

vue.js - Dynamically render items on scroll

Vuejs - Sun, 2017-09-03 21:02

I have list of 100+ items and rendering takes too much time.

I am therefore rendering just empty DIV's with specific height (to reserve the space) and want to render the content when it becomes visible (that means document on scroll).

So, in this code below all 3 items are rendered. BUT the last two items should be blank and its content should be rendered once when they become visible.

What's the best approach?

var myItems = [{name: 'New item'}, {name:'Another'}, {name:'Third'}]; new Vue({ el: '#app', data: { items : myItems } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script> <div id="app"> <div class="items" v-show="items.length"> <div v-for="item in items" style="border:2px solid red;height:700px"> <!-- following content should be rendered only when the item becomes visible --> <div class="content-when-visible">{{ item.name }}</div> </div> </div> </div>

Categories: Software

Vue JS 2: Bind computed property to data attribute

Vuejs - Sun, 2017-09-03 20:57

I have a data object in Vue.js 2 that looks like this:

data: { items: [ { value1: 10, value2: 10, valuesum: "" }, { value1: 10, value2: 100, valuesum: "", } ]

I render that data object in a table and run calculations on it. I want the valuesum property to be computed and stored in each object somehow. In other words, I want the code to essentially perform this:

data: { items: [ { value1: 10, value2: 10, valuesum: {{ value1 + value2 }} //20 }, { value1: 10, value2: 100, valuesum: {{ value1 + value2 }} //110 } ]

The computed attribute doesn't seem to be able to accomplish this. I tried to use the following function but this does not work:

function (index) { for (let i = 0; i < this.items.length; i++ ){ return this.items[index].value1 + this.items[index].value2; } }

The closest I have managed to get to an answer is by doing the calculation inline, but I can't bind its result to the items.total object. My HTML looks like this:

<table id="table"> <thead> <tr> <td>Value 1</td> <td>Value 2</td> <td>Sum</td> </tr> </thead> <tbody> <tr v-for="item in items"> <td><input type="number" v-model="item.value1"></td> <td><input type="number" v-model="item.value2"></td> <td> {{ item.value1 + item.value2 }} </td> </tr> </tbody> </table>

But I can't add v-model to it, since it's not an input. I'd like to avoid adding a readonly <input> to the column, since that doesn't seem like the best solution and isn't very elegant.

Categories: Software

vue select doesn't show initial value

Vuejs - Sun, 2017-09-03 20:48

I am trying to show the initial value of a array of objects like this:

tableStyes[ {Id: 1, style: "blabla1}, {Id: 2, style: "blabla2"} ]

basicly i am using a computer method to give me the array from vuex store

tableStyles () { return this.$store.getters.getTableStyles },

i am doing the select this way:

<select class="form-control" v-model="table.tableStyle"> <option v-for="(item,key) in tableStyles" :value="item.Id"> {{ item.style }} </option> </select>

i want to get the value based on the id, i mean i want to get the text associated to the id, and the id is table.tableStyle, that is 1 at the begin that should be the selected item, but somehow it doesn't work :/.

Any help?

Categories: Software

How to send data to component in vue js?

Vuejs - Sun, 2017-09-03 18:48

How to send data to a component in vue js ? I got data/response from the server on button click.Now I want to send this response to component and display on list using v-for. here is my code https://plnkr.co/edit/EAaEekLtoiGPvxkmAtrt?p=preview

// Code goes here var store = new Vuex.Store({ state: { Item: [] }, mutations: { getItems: function (state) { } }, actions: { fetchData:function (context) { Vue.http.get('data.json').then(function(response){ alert('dd') }, function(error){ console.log(error.statusText); }); } } }) var httprequest = Vue.extend({ "template": '#http_template', data: function () { return { items: store.state.Item } }, methods: { fetchData: function () { store.dispatch('fetchData') }, } }) Vue.component('httprequest', httprequest); var app = new Vue({ el: '#App', data: {}, });
Categories: Software

Return multiple values from a computed filter in Vue JS

Vuejs - Sun, 2017-09-03 18:19

I have a search box where when the user inputs an artist name and it shows a list of artists that match the user input.

I want to display the artist image next to the artist name in the search.

I have an object that contains the following. Artist Name as key and path to image as value

Radiohead: 'path_to_image', Elliott Smith:'path_to_image'

I have a computed property that filters the artists name for search.

computed: { filteredArtists() { return Object.keys(this.artistsList).filter((artist) => { return artist.match(this.artistName) }) }

},

and in my template I'm iterating throgh the values

<ul class="searchFliter" v-for="artist in filteredArtists"> <li v-text="artist"></li> </ul>

I can't find a way to manage that with computed values. I can easily iterate over my object and display both Artist name and Artist image but can't filter it.

Thanks in advance

Categories: Software

Vue router for multiple navigations

Vuejs - Sun, 2017-09-03 17:40

I am using vuejs router as frontend for my app which is getting deeper and deeper day by day. Now my client has asked me to create a new section for my site which basically is a complete website in its nature. hence will have a different navigation. Now my question is how do i make it happen.

one solution is to use a variable or something to hide the main navigation and show this sub-navigation bar. This doesn't feel neat to me. ' I open to any suggestions.

Categories: Software

array copy keeps changing without edition

Vuejs - Sun, 2017-09-03 17:37

I am working on a simple list builder, i can create and edit the list, basicly i have a modal where i build the list after that i can edit it, my issue is if i edit and change the number of items inside the list without pressing the edit, the changes to the list apply. all the rest that i change and don't press edit, works well.

Here is a example:

my modal edition:

data () { return { newItem: '', listItem: 0, showNewItem: false, bulletList: { currentSymbol: '•', key: 'List', items: [ ], ordered: false, numbering: 38 }, listOptions: [ { 'symbol': '•', 'number': 37 }, { 'symbol': '1', 'number': 1 } ] } },

in my edition the only thing that can change is the bulletList object, so when i press the edition section it loads the object like this:

mounted () { console.log('MOUNTED', this.bulletList.items) var sectionKey = this.$store.getters.getCurrentEditionKey this.bulletList =_.clone(this.$store.getters.getDocumentAttributes[sectionKey]) }

when i add a item to edit my bulletList and close the configuration modal it added(it shouldn't) the only thing i do when i add a new item is to push it to the local object inside my component, and not the one that i copied from vuex store, strange issue any help? it has something to do with the array behaviour?

removeItem () { this.bulletList.items.splice(this.listItem, 1) this.listItem = 0 }, addNewItem () { this.bulletList.items.push(this.newItem) this.newItem = '' },
Categories: Software

Pages