Software

Render HTML in Vue.js Grid

Vuejs - Fri, 2017-08-25 18:06

I'm currently looking at the following example: https://vuejs.org/v2/examples/grid-component.html

and my goal is to have the data be HTML that is rendered. Here's what I've tried:

// bootstrap the demo var demo = new Vue({ el: '#demo', data: { searchQuery: '', gridColumns: ['html'], gridData: [ { html: '{{{<html><div><p>test</p></div></html>}}}', name: 'Chuck Norris', power: Infinity }, { name: '<html><div><p>test</p></div></html>', power: 9000 }, { name: '<div v-html="<p>Test</p>"></div>', power: 7000 }, ] } });

This is a proof of concept before I clean up the other data points. The requirements call for having a single-column grid that has boxes as it's items, with each box being a snapshot of rendered HTML.

We don't want to have to render the HTML to images if possible. In production, the HTML will be the content html of email mailings. Everything else, code wise, is the same as the example posted in the above link.

Thanks

Categories: Software

How to mix two arrays of one object in js?

Vuejs - Fri, 2017-08-25 18:02

I am going to build a computer game to study economic terms in Russian for Chinese students.

The script of my game is:

  1. I have 5 random Chinese and five random Russain cards with economic terms. Upper there are Chinese ones, below are Russian ones. Cards are made like jpg files in Photoshop.
  2. The user must find the particular term in Chinese, then the same one in Russian.
  3. To make this game more complicated, I should mix terms. Now Chinese terms is just over its Russian translation. I want terms and translation to be mix in random. But Chinese terms should be always over Russian.

Here is my code:

HTML:

<div id="game"> <div class="container"> <div class = "chinese"> <game-card-chinese v-for="card in getSplicedArray(5)" v-bind:gameprop="card"> </game-card-chinese> </div> <div class = "russian"> <game-card-russian v-for="card in getSplicedArray(5)" v-bind:gameprop="card"> </game-card-russian> </div> </div>

JS:

Vue.component('game-card-chinese', { props: ['gameprop'], template: '<span><img :src = "gameprop.src_chinese" data-toggle="tooltip" v-bind:title="gameprop.name"/></span>' }) Vue.component('game-card-russian', { props: ['gameprop'], template: '<span><img :src = "gameprop.src_russian" data-toggle="tooltip" v-bind:title="gameprop.description"/></span>' }) var game = new Vue({ el: '#game', data: { splicedCardList:[], cardList: [ { id: 0, src_chinese: 'img/actions/actions_chinese.jpg', src_russian: 'img/actions/actions_russian.jpg', name: "Акция", description: "Акция – ценная бумага, свидетельствующая о внесении средств в капитал акционерного общества и дающая право на получение части прибыли в виде дивидендов" }, { id: 1, src_chinese: 'img/actives/actives_chinese.jpg', src_russian: 'img/actives/actives_russian.jpg', name: "Актив", description: "Актив: часть бухгалтерского баланса (левая сторона), отражающая состав и стоимость имущества организации на определённую дату. Совокупность имущества, принадлежащего юридическому лицу или предпринимателю" }, { id: 2, src_chinese: 'img/arenda/arenda_chinese.jpg', src_russian: 'img/arenda/arenda_russian.jpg', name: "Аренда", description: "Аренда — форма имущественного договора, при которой собственность передаётся во временное владение и пользование (или только во временное пользование) арендатору за арендную плату" }, { id: 3, src_chinese: 'img/amortization/amortization_chinese.jpg', src_russian: 'img/amortization/amortization_russian.jpg', name: "Амортизация", description: "Амортизация — процесс переноса по частям стоимости основных средств и нематериальных активов по мере их физического или морального износа на стоимость производимой продукции (работ, услуг)" }, { id: 4, src_chinese: 'img/assignation/assignation_chinese.jpg', src_russian: 'img/assignation/assignation_russian.jpg', name: "Ассигновать", description: "Ассигновать - Назначить отпуск денег." }, { id: 5, src_chinese: 'img/bankruption/bankruption_chinese.jpg', src_russian: 'img/bankruption/bankruption_russian.jpg', name: "Банкротство", description: "Банкротство — признанная уполномоченным государственным органом неспособность должника (гражданина, организации, или государства) удовлетворить в полном объёме требования кредиторов по денежным обязательствам и (или) исполнить обязанность по уплате обязательных государственных платежей" }, ] }, methods: { getSplicedArray: function(itemLength){ if(this.splicedCardList.length != 0){ return this.splicedCardList; } var itemIndex; for (var i = 0; i<itemLength; i++){ itemIndex = Math.floor(Math.random() * this.cardList.length); this.splicedCardList.push(this.cardList[itemIndex]); this.cardList.splice(itemIndex,1); } return this.splicedCardList; }, mixArray: function(){ var arr1 = [this.cardList.src_chinese]; var arr2 = [this.cardList.src_russian]; var arr3 = new Array(); for(var i in arr1){ var shared = false; for (var j in arr2) if (arr2[j].name == arr1[i].name) { shared = true; break; } if(!shared) arr3.push(arr1[i]) } arr3 = arr3.concat(arr2); },

Where is my mistake? What should I do?

Categories: Software

Cannot find function from imported module

Vuejs - Fri, 2017-08-25 17:38

first of all thanks in advance for the feedback. As I am new to es6 and vuejs I'm starting to have problems using imported Services module throughout the application. The end goal would be to move everything that uses Axios to one BaseService too.

[Vue warn]: Error in mounted hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__services_AuthService__.a.getCurrentUser is not a function"

AuthService.js

import BaseService from './BaseService' export default class AuthService { setCurretUser( user ) { localStorage.setItem("currentUser", user); } getCurrentUser() { return localStorage.getItem("currenUser"); } }

App.vue

import Axios from 'axios' import Navbar from './partials/Navbar' import Sidebar from './partials/Sidebar' import AuthService from '../services/AuthService' export default { name: 'app', components: { Navbar, Sidebar }, mounted() { console.log('Component mounted.') }, created() { Axios.get('api/user') .then(function (response) { AuthService.setCurrentUser(response.data); console.log(response); }) .catch(function (error) { console.log(error); }); } }
Categories: Software

"export 'store' was not found in '../store'

Vuejs - Fri, 2017-08-25 17:25

HI all I am trying to import my store into my Vuex Route-Gard.

router/auth-guard.js

import {store} from '../store' export default (to, from, next) => { if (store.getters.user) { next() } else { next('/login') } }

store/index.js

import {store} from '../store' export default (to, from, next) => { if (store.getters.user) { next() } else { next('/login') } }

The error I am getting export 'store' was not found in '../store'

my vue set up

"dependencies": { "firebase": "^4.3.0", "vue": "^2.3.3", "vue-router": "^2.6.0", "vuex": "^2.3.1"
Categories: Software

Vue pagination not working only in Chrome

Vuejs - Fri, 2017-08-25 17:02

I have a pagination component built with Vue 1, for which I am receiving data from Laravel pagination:

<template> <div class="row"> <div class="col-md-8"> <div v-if="zeroVideos">No videos found for "{{ query }}""</div> </div> <div class="col-md-8"> <single-video v-for="video in videos" :video="video"></single-video> </div> </div> <div class="row justify-content-center"> <pages v-if="meta && videos.length && showPagination" for="videos" :pagination="meta.pagination"></pages> </div> </template> <script> import eventHub from '../events.js' export default { props: ['query'], data () { return { videos: [], meta: null, showPagination: false, zeroVideos: false, } }, methods: { getVideos (page) { this.$http.get('/search/videos?q=' + this.query + '&page=' + page).then((response) => { this.videos = response.data.data this.meta = response.data.meta this.showPagination = response.data.meta.pagination.total_pages > 1 console.log('Videos ' + response.data.meta.pagination.total) this.zeroVideos = response.data.meta.pagination.total < 1 eventHub.$emit('videos.counter', response.data.meta.pagination.total) }) } }, ready() { this.getVideos(1) eventHub.$on('videos.switched-page', this.getVideos) } } </script>

For some reason, after I have updated my chrome, pagination stopped working and I am getting undefined for response.data.meta , but on checking the network tab in the console, I am sending the data from the backend:

data[{id: 43, uid: "15883245ef3de1",…}, {id: 44, uid: "15883245ef3de2",…},…] meta:{pagination: {total: 8, count: 8, per_page: 20, current_page: 1, total_pages: 1, links: []}}

The pagination works fine on IE, Firefox and Safari, but on Chrome I have problems after updating. What is wrong?

Categories: Software

Use VueJs to save a template

Vuejs - Fri, 2017-08-25 16:56

My project currently is made with VueJS. Now, we need to process a certain template with the input data, then store the result and use it to send an email (for example).

Can i render a template with the user data and save it? how?

I don't want to use another library for this purpose, unless We can't do with VueJS

Categories: Software

Vuejs html element displayed in wrong order

Vuejs - Fri, 2017-08-25 16:19

I have a vue component with the following html structure:

<div v-for="ea in list1"> <competency></competency> </div> <div class="secured-break"> ** Lorem ipsum </div> <div v-for="ea in list2"> <competency></competency> </div>

When I display this html in the browser I would expect a list of items, followed by the ** Lorem ipsum text and then the second list of items. However, when I display this html, I see the ** Lorem ipsum first, then the results of list1 immediately followed by the results of list2. Why are these items displayed out of order?

css .secured-break { border-top: 1px solid #C0C0C0; font: 10px arial; font-style: italic; width: 880px; }
Categories: Software

Can i send template to label?

Vuejs - Fri, 2017-08-25 15:27

I'm using Element Ui for a tables

Say me please. How i can send template to label?

Categories: Software

SyntaxError: Unexpected token 'const' -- despite the fact that I replaced const

Vuejs - Fri, 2017-08-25 14:04

I'm trying to export my firebase app so I can call it inside of mocha test specs as well as within the source code I'm trying to test.

My Mocha test spec looks like this:

import Vue from 'vue' import Edit from '@/components/Edit' import filedata from '../../../static/filedata.js' import submitFile from '../../../helpers/submitFile.js' import firebaseapp from '../../../src/db.js' var db = firebaseapp.database() var storage = firebaseapp.storage() describe('Edit.vue', () => { it('should let me add files without choosing a category', () => { // add files to appear on the homepage var Constructor = Vue.extend(Edit) var vm = new Constructor().$mount() console.log(filedata + ' is the file data') var ref = storage.ref('categories') console.log(ref) submitFile(filedata) }) ...

And the submitFile file looks like this:

var firebaseapp = require('../src/db.js') console.log('the app is: ' + firebaseapp) var db = firebaseapp.database() var storage = firebaseapp.storage() module.exports = function(files){ // is the function being called from the test environment? if(files){ console.log(files) } else { // function called from src -- files were null var files = this.$refs.upload.uploadFiles; } var storageRef = storage.ref(); var pdfsRef = storageRef.child('files'); // var self = this; console.log('the files length is ' + files.length) files.forEach(function(file){ var file = file['raw']; var name = file['name'] var fileref = storageRef.child(name); var uploadTask = fileref.put(file); uploadTask.then(function(snapshot){ console.log('uploaded'); var url = snapshot.downloadURL; self.gettext(url, name); }); try { uploadTask.on('state_changed', function(snapshot){ // Observe state change events such as progress, pause, and resume // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded self.uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log(self.uploadProgress + ' is the upload progress.'); switch (snapshot.state) { case app.storage.TaskState.PAUSED: // or 'paused' console.log('Upload is paused'); break; case app.storage.TaskState.RUNNING: // or 'running' console.log('Upload is running'); break; } }, function(error) { // Handle unsuccessful uploads }, function() { // Handle successful uploads on complete // For instance, get the download URL: https://firebasestorage.googleapis.com/... var downloadURL = uploadTask.snapshot.downloadURL; }); } catch(e){ console.log(e) } }) }

Lastly, here's what db.js looks like:

var Firebase = require('firebase')//import Firebase from 'firebase' var config = { ... }; var app = Firebase.initializeApp(config) /// USED TO BE CONST APP export default app

What's very strange is that when I run npm run unit, I get an error telling me that const is not recognized.

SyntaxError: Unexpected token 'const' at webpack:///src/db.js~:11:0 <- index.js:38182

So I went through my db.js file and changed const to var, and I'm getting the exact same error*, no matter how I change the file.

Does anyone have any idea what could be going on?

Categories: Software

How to use img src in vue.js?

Vuejs - Fri, 2017-08-25 14:01

I have this in my vue.js template:

<img src="/media/avatars/{{joke.avatar}}" alt="">

It is inside a loop that renders jokes. Otehr fields are rendered fine, but for the image I get this error in the console:

  • src="/media/avatars/{{joke.avatar}}": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of , use .

I have also use v-bind:src="... but get invalid expression error.

How can I fix this?

P.S.

I have also tried

<img :src="'/media/avatars/' + joke.avatar" alt="">

As suggested here, but that did not solve the problem. So I don't know how my question can be a duplicate of that.

Categories: Software

Pass click action using array and v-for (Vue.js)

Vuejs - Fri, 2017-08-25 11:51

I am trying to pass through a v-for the text and the @click action of each li. For the text I know how to do it...but for the click action?enter code here

Each item of the array menuOptions (which is in the 'data' part of my Vue component) is structured like this : {action,name}

As "action", I mean the call of a peculiar function of my code, which will be different for each item.

<ul> <li v-for="option in menuOptions" @click="option.action">{{option.name}}</li> </ul>

Do you have some ideas? (I guess that's maybe a pure JS question, but maybe there are possibilities to do it Vue too?)

Categories: Software

Vuejs not reading property from mixins and export NOT FOUND error.

Vuejs - Fri, 2017-08-25 11:21

I have been on this error for 3 days, not sure if this is a bug, but I installed vuejs from vuejs/vue-cli

Using the following instructions:

npm install -g vue-cli vue init webpack foo.com cd foo.com npm install npm run dev

So far it works, now I created a directory structure like this inside src/

— src — assets — filters — config — components Profiles.vue Login.vue profiles.js routes.js main.js

So, in routes.js I have something like this.

// routes.js import ProfilesView from './components/Profiles.vue' import LoginView from './components/Login.vue' const routes = [{ path: '/profiles', component: ProfilesView }, { path: '/login', component: LogoutView }] export default routes

So far, I have no issue with above code, the problem comes from these two below files either profiles.js or Profiles.vue

Here is profiles.js

const profiles = Vue.mixin({ data: function () { return { profiles: [] } }, methods: { fetchProfiles: function(){....}, mounted: function(){ this.fetchProfiles() } }) export default profiles

Here is Profiles.vue

<template lang="html"> <div> {{ profiles }}<div> </template> <script> import { profiles } from '../../profiles' export default { mixins: [profiles], data () { return { profiles: [] } }, mounted () {} } </script> <style lang="css"> </style>

With the above code, I get these errors.

profiles.js:1 Uncaught ReferenceError: Vue is not defined at Object.<anonymous> (profiles.js:1) at __webpack_require__ (bootstrap 1995fd0fa58cb1432d6f:659) at fn (bootstrap 1995fd0fa58cb1432d6f:85) at Object.defineProperty.value (app.js:55806) at __webpack_require__ (bootstrap 1995fd0fa58cb1432d6f:659) at fn (bootstrap 1995fd0fa58cb1432d6f:85) at Object.<anonymous> (Profiles.vue:7) at __webpack_require__ (bootstrap 1995fd0fa58cb1432d6f:659) at fn (bootstrap 1995fd0fa58cb1432d6f:85) at Object.__webpack_exports__.a (app.js:56033)

If I add import Vue from 'vue' to profiles.js the above error gets replaced with this one:

Uncaught TypeError: Cannot read property 'components' of undefined at checkComponents (vue.esm.js:1282) at mergeOptions (vue.esm.js:1363) at mergeOptions (vue.esm.js:1379) at Function.Vue.extend (vue.esm.js:4401) at Object.exports.createRecord (index.js:47) at Profiles.vue:26 at Object.<anonymous> (Profiles.vue:30) at __webpack_require__ (bootstrap 625917526b6fc2d04149:659) at fn (bootstrap 625917526b6fc2d04149:85) at Object.__webpack_exports__.a (app.js:56036)

This is complaining about the mixins: [profiles], in profiles.js, I am thinking profiles prop is undefined, but that is not the case. For some reason Profiles.vue is not reading or reading the correct data from profiles.js because I also get this error always:

[HMR] bundle has 1 warnings client.js:161 ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/Profiles.vue 6:11-15 "export 'profiles' was not found in '../../profiles'

It is complaining export default profiles isn't found in profiles.js even though it clearly does. I even tried using require, changing the paths ... everything. Nothing works.

I would appreciate any help with this.

Categories: Software

jQuery plugins not initialised in vuejs when loading a page using vue-router

Vuejs - Fri, 2017-08-25 10:59

I have a collection of jQuery plugins in the file jquery-plugin-collection.js and I initialise the plugins in the file custom.js. When I reload the page, all the plugins are being initialised. but when I load the page using vue-router, the plugins are not initialised. I made alot of google research with no result. Am wondering if am the first to face this issue. You can comment if you want me to add some codes.

Categories: Software

PHPStorm and ES6 arrow functions inside vue template tag

Vuejs - Fri, 2017-08-25 05:54

I'm using PHPStorm 2017.2 and today I faced with some trouble. Is there any way to use arrow functions within vue attributes inside template? Now, i'm getting "expression expected" error highlighted by PHPStorm, when trying to write something like

<template> <button @click="() => {some code... }">Click me</button> </template>

Arrow functions works fine inside script tag, but problem with template tag drives me mad.

Categories: Software

Extending root vue instance

Vuejs - Fri, 2017-08-25 04:22

I have a root Vue 2 instance mounted on every page of my application, and I need to add methods that will be accessed only on two pages of my app. I know I could add those methods in my root Vue instance but I'm not sure if it is the right way to go as those methods will be available from all other pages in the app and they have dependencies that I don't want to import on all pages.

// app.js //## Root Vue Instance window.App = new Vue({ el: '#app', methods: { ... } })

I thought about extending the global Vue prototype on a separate JS file that loads only on the page I need these methods:

// page1.js Vue.prototype.method1 = function(){...}

However on the second page I need to access those methods I will have to repeat myself.

// page2.js Vue.prototype.method1 = function(){...}

What is the recommended approach on this?

Categories: Software

Strategy to learn testing

Vuejs - Fri, 2017-08-25 00:36

I'm working with an app newly built running on JavaScript (vue.js) , Mongodb, Express.js and node.js . My primary responsibility is to perform testing and take care of front end. Can you please suggest tools and software I can learn to facilitate the job and be more effective at it ? Thanks.

Categories: Software

Import a javaScript file in vuejs2 project

Vuejs - Thu, 2017-08-24 23:55

I'm a beginner with Vuejs framework and I'm having a problem in using js libraries in my vue project.. I'll be sooo grateful if anyone could help meee

btw I tried adding this in my main.js file and it didn't work

import template from './assets/js/template.js' Object.definePrototype(Vue.prototype, '$template', { value: template })

template.js is my js file

Categories: Software

Vue js removing node when it shouldn't

Vuejs - Thu, 2017-08-24 23:45

I have a django project where text is annotated. Once the text is highlighted it should bring up a create button in order to actually create the annotations. The highlighting is done using js rects. This all works fine except when you select the first character of the entire body of text, then the button doesn't show up or is removed. You could highlight the first character or an entire sentence and as long as the first character is selected then the create button is either removed or doesn't show. I'm using vue.js to manipulate the buttons. From the debugging that I have done, it is being done in the vue.js source code but I am having a hard time figuring out whats triggering the node removal. Any ideas as to what could be causing this? Any ideas are greatly appreciated

Categories: Software

vue.js: vue-multiselect, clearing input value after selected

Vuejs - Thu, 2017-08-24 23:13

I am working on my project in laravel/vue.js and I decided to use simple vue-multiselect to choose categories from my database. Thing is I want to clear the value from input field (to look for item in list).

My multiselect component:

<multiselect v-model="value" placeholder="Find the category" label="category_name" :options="categories" @input="addReceiversFromCategory"> </multiselect>

I try to clear an v-model but it work only on first select after page load (and also it is not a smart way..). Last thing i try was the :clear-on-select="true" but it works onlu when multiple is true (which I dont want to be true). I think its simple to do but I didn't find any way in documentation doc

Categories: Software

Binding events to window in Vue.js

Vuejs - Thu, 2017-08-24 22:58

I am quite new to Vue.js. Recently, I have encountered an issue with attaching/detaching keyboard events to window inside one of my components. Here are my methods:

created() { this.initHotkeys(); }, beforeDestroy() { this.discardListeners(); }, methods: { initHotkeys() { window.addEventListener('keyup', this.processHotkey.bind(this)); window.addEventListener('keydown', this.removeDefaultBehavior.bind(this)); }, discardListeners() { window.removeEventListener('keyup', this.processHotkey.bind(this)); window.removeEventListener('keydown', this.removeDefaultBehavior.bind(this)); }, ....

The events attach and fire up without any issues. However, when I switch components, the events still remain attached to the window. After a bunch of attempts, I found out that if I remove the .bind(this) part from all the callbacks, events detach successfully.

Can anyone, please, explain me why this happens?

Thank you in advance!

Categories: Software

Pages