Software

Vue.js server side rendering with axios

Vuejs - Thu, 2017-08-03 12:19

In a vue.js app with server side rendering, taking inspiration from the Vue Hn project and the vue ssr tutorial.

There is an /api/index.js file making the requests to an api which return a promise like specified here.

import data from './data' // just an a json object export function fetchList() { return new Promise((resolve, reject) => { if (true) { resolve(data) } else { reject('error') } }) }

So far so good, everything works fine: the page is server side rendered on first load and then things happen client side.

Now, I try to make a real api request with axios:

import axios from 'axios' const apiurl = `https://my-api.com/api/v1` export function fetchList() { // the api call works fine in postman return axios.get(`${apiurl}/posts`) .then(response => { return response.data }) .catch(error => { return error }) }

It does not working anymore:

  • the data are not fetched on the server (and not in the page on first load),
  • the first page load is really slow (10s or more)
  • after first page load, it still works fine client side…

Any idea on what is going wrong with this axios api call?

Categories: Software

Deleted values are removed only after page refresh in vue js

Vuejs - Thu, 2017-08-03 12:16

I need to delete the data in an id by using delete button, the values were got deleted but it was still displaying the values .. The deleted values were removed only after we doing a refresh of a page. How can i make the data gets deleted and removed from the table immediately after click event without doing page refresh?

Delete button:

<button class="btn btn-primary" v-on:click="deleteItems(booking.id)">Delete</button>

Script of delete:

methods: { deleteItems(id) { axios.delete(config.apiDomain+'/Booking/deleteItems/'+id).then((response)=>{ this.$router.push('/admin/booking'); console.log(id); }); }, }, mounted() { axios.get(config.apiDomain+'/Booking').then((response)=>this.items = response.data); }
Categories: Software

Vuejs linking between slots

Vuejs - Thu, 2017-08-03 12:08

I have a layout that i thought i'd implement using slots. There is basically a slot for a left menu and a slot for content. I'm trying to make a click inside a menu slot to change the component inside the content slot. Here is how my component, using the slotted layout looks like:

<template> <split-content> <-- this is the component that handles the layout <div slot="content-left"> <router-link to="/users/1">first user</router-link> </div> <div slot="content-right"> <router-view></router-view> </div> </split-content> </template>

So what i want to happen is for the router-link component to use the router-view defined in the content-right slot. But i guess that's probably impossible. The entire component is overwritten when i click on the link. Any ideas?

Categories: Software

render variable in template vuejs

Vuejs - Thu, 2017-08-03 11:54
<li v-for="set in indirect_arr"> {{set.wp}} - {{set.bus1}} - {{set.bus2}} </li>

indirect_arr -> array of Objects(say, set).

Object Structure ->

set : { wp: '', bus1: [], bus2:[] }

bus1 & bus2 are reflected on dom as Array.

I want them as single elements .

I tried -> <li v-for="bus in set.bus1">{{bus}}</li> . Got Error -> set not defined !

Categories: Software

transition-group behaviour not working like docs say

Vuejs - Thu, 2017-08-03 11:45

I have this.

<transition-group name="slide" tag="div"> <div v-for="number in [currentSlide]" v-bind:key="number"> <p>{{ items[0].titulo }}</p> </div> </transition-group>

with this method

nextSlide: function () { if (this.currentSlide >= 6) { this.currentSlide = 0 } else { this.currentSlide++ } setTimeout(() => { this.items.pop() this.items.push(this.Slides.slides[this.currentSlide]) this.nextSlide() }, 4000) }

So, basically, elements appear (with animation) at the same time, when one is leaving, the other one is enter at the same time, but, not the same space, actually the next element to render appears down the first, and then takes it place.

Using mode="out-in" ins´t working

Categories: Software

vue.js: Route guard wait for async value

Vuejs - Thu, 2017-08-03 10:58

As in every application I have a few routes. For example (router/index.js excerpt):

[{ path: '/reporting', name: 'Reporting', component: reporting, meta: { adminOnly: true } }, ...]

As you can see in the route definition, when accessing reporting the user needs to have admin permissions, which is a property in a vuex store. The problem: This property is async and is of course false when initially accessing in the guard. How can I make my guard wait for it?

Guard:

if (to.matched.some(route => route.meta.adminOnly)) { if (store.getters.userInfo.isAdmin) { next() } else { next('/') } } else { next() }
Categories: Software

IE not loading all page requests

Vuejs - Thu, 2017-08-03 10:52

I'm trying to debug why my site is failing to load properly on IE 11. On chrome my home page makes an api call (I'm using Laravel backend and Vuejs with axios in the front end) to fetch all the users however, when I load the page in IE 11 no users appear, no api call is made (in the network tab on the developer tools) and there are no errors showing in the developer tools console.

Can anyone give me any tips as to how I can start debugging this?

Any help would be much appreciated.

Thanks

Categories: Software

why does the scss build fail?

Vuejs - Thu, 2017-08-03 10:24

In my vue-cli webpack project, I try to include mixin.scss and base.scss in my global index.scss. But it fails:

enter image description here

I am really confused. Is the syntax wrong?

Categories: Software

Start range in v-for="n in 10" from zero

Vuejs - Thu, 2017-08-03 09:50

I want to start the range from 0 instead of 1 in v-for="n in 10" which results in 1 2 3 .... 10 Is there a way to do it in Vuejs?

Categories: Software

Confused with Vuex commit/dispatch in simple VueJS test

Vuejs - Thu, 2017-08-03 08:53

From the book:

To invoke a mutation handler, you need to call store.commit with its type: store.commit('increment')

Mutations must always be synchronous.

From the book:

Actions commit mutations ( can be asynchronous )

Actions are triggered with the store.dispatch method: store.dispatch('increment')

So it's action -> mutation -> new state most of the time.

So what's confusing me, is the very simple example, whereby I'm trying to show the asynchronous result of an object getTest

See this pen

Why can't Vue see that I'm not calling a mutation, but an action when the component loads?

Categories: Software

Best practices Vue.js

Vuejs - Thu, 2017-08-03 06:31

I have been trying Vue.js with ASP.Net Core for the last week and it seems quite powerful. However, I have seen different approaches in the way how files are organized and modules written.

In the javascript spatemplate, they use, I would say this structure with ts, html, css files:

|_components |_counter *counter.ts *counter.css *counter.html

In other starter Vue.js templates, we have this structure with one single vue file:

|_components |_counter.vue

Is there a limitation/advantage in using one over the other? Is one being more recent and should superseed the other format?

I have also see that they are different way of writing component for Vue in Typescript.

The default one presented on the Vue website and the other way using the vue-class-component or the vue-property-decorator which looks more natural to me and is recommended on the Vue website as it seems to solve some issues: link.

Again if it is that good, why shouldn't it become the standard? Does the default style gives more flexibility compared with the 'vue-class-component' style?

Sorry for the basic questions, just trying to get the good directions from the beginning.

Thank you

Sylvain

Categories: Software

Vuetify error : ncaught SyntaxError: Unexpected token export

Vuejs - Thu, 2017-08-03 05:35

im trying to use vuetify now, but i really confuse how to use it. I have used CDN, and copy-paste the html and javascript code from vuetify.js, but it doesnt work at all. It returned error uncaught SyntaxError: Unexpected token export. This is the html code:

<template> <v-card height="200px"> <v-bottom-nav absolute shift value="true" :class="{ 'blue-grey': e2 === 1, 'teal': e2 === 2, 'brown': e2 === 3, 'brown lighten-1': e2 === 4 }" > <v-btn dark @click.native="e2 = 1" :value="e2 === 1"> <span>Video</span> <v-icon>ondemand_video</v-icon> </v-btn> <v-btn dark @click.native="e2 = 2" :value="e2 === 2"> <span>Music</span> <v-icon>music_note</v-icon> </v-btn> <v-btn dark @click.native="e2 = 3" :value="e2 === 3"> <span>Book</span> <v-icon>book</v-icon> </v-btn> <v-btn dark @click.native="e2 = 4" :value="e2 === 4"> <span>Image</span> <v-icon>image</v-icon> </v-btn> </v-bottom-nav> </v-card> </template> and javascript code: <script> export default { data () { return { e2: 3 } } } </script>
Categories: Software

Vue.js 2/Javascript mouseover method applying events on mousein and mouseout

Vuejs - Thu, 2017-08-03 03:52

my question is just how to run a Vue method one time on mouseover, rather than running it both on mousein and on mouseout.

For example here is the template I am using in Vue, where I am looping through some data and I want a method called showSkill() to fire only once, where it is currently firing both on mousein/mouseout:

<div class="col-md-3" v-for="skill in skills" :key="skill.id"> <label :for="skill.nickname">{{ skill.name }}</label> <div :id="skill.nickname" @mouseover="showSkill(skill)"></div> </div>

Here is the method:

showSkill(skill) { jQuery(`#${skill.nickname}`).empty() this.drawDonutChart(`#${skill.nickname}`, (skill.level/100).toFixed(2) * 100, 200, 200, '.35em') },

I think this is an event issue more than a Vue issue. Any suggestions would be greatly appreciated!

Categories: Software

how to reference function, and variables dynamically in JS

Vuejs - Thu, 2017-08-03 03:39

After asking a few questions on here and confirming that js does not pass references, only values, the question becomes, how do you make dynamic decision making. Let me explain. Right now i use many switch statements in a complicated form i am creating. But i would like to create an array that has many objects that contain the condition to be met and the variable or function to execute. The way i achieve this right now is to name the variable in plain text and execute it in brackets like so: this[nameofvar] = false where 'nameofvar' is the string store in the array object. This to me is bad on so many level and hackish.

So how do you do it?

Categories: Software

How to turn FileReader image preview example into Vue component?

Vuejs - Thu, 2017-08-03 02:39

There's an example from MDN on how to use FileReader to show a preview image:

function handleFiles(files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /^image\//; if (!imageType.test(file.type)) { continue; } var img = document.createElement("img"); img.classList.add("obj"); img.file = file; preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed. var reader = new FileReader(); reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); } }

I'm wondering how to use this in a Vue component. It seems to me the asynchronous part isn't that easy to handle, but I'm new to Vue, and maybe that's an advanced feature.

Categories: Software

Overriding props before displaying

Vuejs - Thu, 2017-08-03 02:29

In Vue, is there a way to override/manipulate the props data before displaying it in the view by setting a method, or is there an switch or if which I can use inside the component template?

So basically, if the props is "hello", I want to display it like "Hello World."

What is the proper way of achieving this in vue?

Categories: Software

Component v for doesn't recognise prop, if not explicitly declared while initializing object in root

Vuejs - Thu, 2017-08-03 01:48

In my root, I am declaring my (multidimensinal) object in data like so:

var app = new Vue({ el: '#root', data: { accounts: {} }

If I send the props like this:

<div id="root"> <my-component :accounts="accounts"></my-component> </div>

Also in component, accept props. In the component, I also have the template that I perform a for loop.

Vue.component('my-component', { props: ['accounts'], template ` <div> <another-component v-for="(x, i) in accounts"></another-component> </div> ` })

In this case, where while I am initializing the accounts in the root, if I give it an empty object, it won't perform the loop.

If in for loop, instead of accounts, I use a digit, it performs the loop.

Also, while initializing in the root, if I become explicit...

accountTypes : { 1: [], 2: [] },

...the for loop works. However, this time I get another error:

Avoid using non-primitive value as key, use string/number value instead.

Also, I don't want to be explicit on 1 and 2, sometimes I don't want 2 to be there at all.

I am filling up accounts with a method in my root, binded to checkbox @change.

methods: { accountSelected() { this.pushValue(index, name) }, pushValue(key, value) { var obj = this.accounts if (obj.hasOwnProperty(key)) { var idx = $.inArray(value, obj[key]); if (idx == -1) { obj[key].push(value); } } else { obj[key] = [value]; } }, }
Categories: Software

Failed to mount component: template or render function not defined

Vuejs - Thu, 2017-08-03 01:24

I'm trying to build a very simple vue app that displays a modal. I'm using sweet-modal-vue. I am using webpack to bundle my app, primarily so that I can easily import sweet-modal-view into my app.

Something is breaking somewhere in the process and whenever I open my index.html file I get this error:

Failed to mount component: template or render function not defined. Found in <SweetModal>

After looking for a solution I found almost everyone who had this problem solved it by aliasing vue to the full compiler build, as described here. This did not work for me.

Any help would be greatly appreciated, I've been banging my head against this for hours.

Versions:

Vue: 2.8.2 sweet-modal-vue: 5.3.0 Webpack: 3.4.1

Here are the relevant files, let me know if you'd like to see more:

main.js:

import Vue from 'vue'; import App from './app.vue'; import { SweetModal, SweetModalTab } from 'sweet-modal-vue'; new Vue({ el: '#myapp', components: { SweetModal, SweetModalTab, App }, data: { message: "Hello Vue" }, methods: { openModal: function() { console.log(SweetModal); this.$refs.modal.open(); } } })

index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vue Example</title> </head> <body> <div id="myapp"> <app></app> <h3>{{ message }}</h3> <sweet-modal ref="modal" icon="success"> This is a success!! </sweet-modal> Accurate <button v-on:click="openModal()">Modal</button> </div> </body> <script src="dist/build.js"></script> </html>

webpack.config.js

module.exports = { // This is the "main" file which should include all other modules context: __dirname, entry: __dirname + '/src/main.js', // Where should the compiled file go? output: { // To the `dist` folder path: __dirname + '/dist', publicPath: 'dist/', // With the filename `build.js` so it's dist/build.js filename: 'build.js' }, module: { // Special compilation rules rules: [ { // I tried this option as well, it didn't help // test: /\.vue$/, // loader: 'vue-loader', // options: { // loaders: { // // {{#sass}} // // Since sass-loader (weirdly) has SCSS as its default parse mode, we map // // the "scss" and "sass" values for the lang attribute to the right configs here. // // other preprocessors should work out of the box, no loader config like this necessary. // 'scss': 'vue-style-loader!css-loader!sass-loader', // 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // // {{/sass}} // } // // other vue-loader options go here // } test: /\.vue$/, loader: 'vue-loader', options: { loaders: { // Customize to your liking js: 'babel-loader', scss: [ 'style-loader', 'css-loader', 'sass-loader' ] } } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {'vue$': 'vue/dist/vue.esm.js'} } }
Categories: Software

Vue is not defined C9

Vuejs - Thu, 2017-08-03 00:55

Hey guys I am trying to get vue.js up and running for C9 but I wasn't able to find good resources for how to run it. When I try to run this app I get a Reference Error "Vue is not defined" Here is my index.html:

<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <link href = "styles.css" rel = "stylesheet"/> <title>VueJS tutorials</title> <script src="https://unpkg.com/vue"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script> </head> <body> <div id = "vue-app"> <h1>{{name}}</h1> </div> <script src = "app.js"></script> </body> </html>

And here is the part where I am getting the error in app.js:

new Vue({ el:'vue-app', data:{ name:'Michael' } });

I am currently watching net ninja's tutorial and I am not sure how to fix this error.

Categories: Software

Vue2.0 unaccessible variable

Vuejs - Thu, 2017-08-03 00:48

I've am new at Vue and i've got a problem with unaccessible. I've got two files.

1st is App.vue where is defined <router-view>

<script> export default { name: 'app', data(){ return{ info: false, } }, beforeMount(){ example... this.info= true } } </script>

2nd is component Main.vue which is clear:

<script> export default{ name: 'main', data(){ return{ } }, beforeMount(){ //what i want to do: console.log(App.data().info) //here should be visible true in console log } }

i would like to have accessible in 2nd file the property from file number one. How to do it properly? Thank you in advance

Categories: Software

Pages