Software

following tutorial on vue2 website can't get third party jquery plugin select2 to work

Vuejs - Fri, 2017-07-21 23:27

I tried to implement this:

https://vuejs.org/v2/examples/select2.html

I am not making SPA, although I am using Vue components in my page.

[Vue warn]: Error in mounted hook: "TypeError: $(...).select2 is not a function"

found in

I get this error

Error in mounted hook: "TypeError: $(...).select2 is not a function" found in <Select2> at C:\laragon\www\lara\resources\assets\js\components\ui\Select2.vue

I include both select2 and my vuejs in the html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <script src="{{ asset('js/content_type_blocks.js') }}?{{ str_random(7) }}"></script>

I wonder why do I get the error that select2 is not a function?

Categories: Software

VueRouter and meta fields

Vuejs - Fri, 2017-07-21 23:18

According to the VueRouter documentation, it is possible to add meta fields and globally restrict routes based on their values.

After attempting an implementation as outlined, I get an error: ReferenceError: record is not defined (line 46)

Which corresponds to this line:

if (!hasCookies(record.meta.cookies)) {

Here is the file that has the router-guard logic:

import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ { path : '/authenticate/:id', component : require ('./components/authenticate.vue'), redirect: '/here', }, // can only get here if the passcode has been filled out { path : '/client/create', component : require('./components/createClientForm.vue'), meta : { cookies: ['passcode_cookie'], // need passcode to be able to create the client redirect: '/authenticate/1' // dummy value here for now } }, // can only get here if passcode and client form have been completed { path : '/test/:id', component : require('./components/runTest.vue'), meta : { cookies : ['passcode_cookie', 'client_cookie'], redirect : '/client/create' } } ]; const router = new VueRouter ({ routes, mode: 'history', }); function hasCookies (cookies) { return cookies.every(cookie => document.cookie.indexOf(cookie) !== -1); } router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.cookies)) { // this route requires cookies, check if cookies exist if (!hasCookies(record.meta.cookies)) { next({ path : record.meta.redirect || '/', }) } else { next(); } } else { next(); // make sure to always call next()! } }); const app = new Vue ({ router }).$mount('#app');

Any idea on what I may be doing wrong?

Categories: Software

Vue.js SPA Facebook auth

Vuejs - Fri, 2017-07-21 22:20

I'm making my simple social network with Node.JS, Hapi and Vue. I want to have Facebook login. As Fcebook Auth can't be done in SPA I came up with the following method.

  1. Add login button to SPA. This is link to server route which will redirect request to Facebook
  2. User will log in with facebook
  3. Server will return simple HTML page which will include JWT, and store JWT in browser's session store
  4. that simple page will than redirect browser to SPA

Is there better way to do it? Should I somehow place JWT in SPA index.html page??

Categories: Software

Vue method causing v-for infinite loop

Vuejs - Fri, 2017-07-21 21:36

I'm using a Vue JS method to test if data exists in firebase and if so evaluate the v-if to true I have a method that works, but then it keep looping. I just learned that altering the state can cause the v-for to re-render and thus the infinite loop, but I'm having trouble applying this knowledge to my method. Here is my issue:

HTML:

<li v-for="..."> <button v-if="isAttending(report)" @click="qualify(report)"> View </button

And the Method:

isAttending (report) { var theUser = this.user.user.displayName console.log(theUser) reportsRef.child(report['.key']).child('participants').once('value', function (snapshot) { if (snapshot.hasChild(theUser)) { console.log('exists') } }) }

How can I make this so it doesn't alter state preventing the loop?

Categories: Software

Method to evaluate v-if not working

Vuejs - Fri, 2017-07-21 20:48

I'm not sure if this is possible, but I'm trying to get a method to return truthy falsely for a v-if statement. But right now the button always is true for some reason.

Here's my HTML(Pug):

button(v-if="!isAttending(report)" @click="qualify(report)") RSVP

And my JS (Vue)

methods: { isAttending (report) { var that = this var theReport = report if (that.$firebaseRefs.attending.child(that.user.user.displayName).child(theReport['.key']).child('going') === true) { return true } else { return false } }

Essentially what I am doing it asking firebase is something exists and returning true or false. I'm not convinced this is the best way but have yet to come up with better.

Categories: Software

Is it Possible to lock all routes except one, in vue-router ? Is it secure? Or maybe I should use another method?

Vuejs - Fri, 2017-07-21 20:35

There is an online exam, this exam has 5 pages, there is a count down timer (120 seconds) and 4 questions in each page. After 120 seconds user is automatically transferred to the next page, or he can click on next button before that.

What I want is preventing user from seeing other pages. All pages has to be visible for maximum 120 seconds. User should not be able to click on back button and see previous pages. Is this possible at all ?

I want to create this app with Vuejs and vue-router but I don't know how to implement this with vue-router, I have done some research but got not much result!

Or maybe I should not use vue-router, and use my own simple router, for example :

$("#page1").show(); $("#page2").hide(); $("#page3").hide(); . . // after 120 secs $("#page1").hide(); $("#page2").show(); $("#page3").hide(); . . // this is not secure at all !

I am using Laravel5.4 and VueJs, There is an Ajax request for every question that user answers. Any thoughts are appreciated. Thank you.

Categories: Software

How to keep active listGroup after reload page?

Vuejs - Fri, 2017-07-21 19:32

I'm creating a gallery with the #listGroup bootstrap component. I want when one of the albums in the click change the active #listGroup even the page is reload or refresh. How do I fix this?

HTML/PHP

<div class="container"> <div class="row"> <h2 class="col-xs-12">Gallery</h2> </div><!-- /row --> <div class="row"> <div class="col-xs-12 col-sm-3"> <div class="list-group" id='listGroup'> <?php include 'dismin/pages/koneksi.php'; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; $start_from = ($page-1) * 12; $sql = "SELECT * FROM tbl_album where status='process' ORDER BY albumid DESC LIMIT $start_from, 12"; $rs_result = mysql_query ($sql); ####### Fetch Results From Table ######## $no=0; while ($row = mysql_fetch_assoc($rs_result)) { $aid=$row['albumid']; $aname=$row['name']; ?> <a href="gallery?id=<?php echo $aid; ?>" class="list-group-item" v-bind:class="{ 'active' : isSelected(<?php echo $no; ?>) }" v-on:click="selected = <?php echo $no++; ?>"><?php echo $aname; ?></a> <?php } ?> </div> </div><!-- /col --> <div class="col-xs-12 col-sm-9"> <div class="row"> <?php include "dismin/pages/koneksi.php"; $aid = $_GET['id']; $sql = "SELECT * FROM tbl_gallery where aid=$aid and status='process'"; $num_rows = mysql_num_rows(mysql_query($sql)); ####### Fetch Results From Table ######## $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { $gimage=$row['gimages']; ?> <div class="col-xs-12 col-sm-4"> <a href="#" class="thumbnail"> <img src="dismin/pages/galeri/aksi/gupload/<?php echo $gimage; ?>"> </a> </div><!-- /col --> <?php } ?> </div><!-- /row --> </div><!-- /col --> </div><!-- /row --> </div><!-- /container -->

JAVASCRIPT

new Vue({ el: '#listGroup', data: { selected: 0 }, methods: { isSelected: function (i) { return i === this.selected } } })
Categories: Software

Getting undefined property from Ajax response nested object

Vuejs - Fri, 2017-07-21 19:22

I have the following ajax response from the API:

{ "data": [ { "id": 16, "sender_id": 1, "text": "Test", "created_at": "2017-07-21 15:42:08", "updated_at": "2017-07-21 15:42:08", "sender": { "data": { "id": 1, "name": "John Doe", "email": "john@doe.co", "mobile": "+1875446799976", "photo_url": "https://example.co/storage/profiles/0H6Rkwsrlns0R1PY03Mta2qIhdPhV7N19jaagH3m.jpeg", "first_login": 0, "uses_two_factor_auth": false, "two_factor_reset_code": null, "current_team_id": 1, "stripe_id": null, "current_billing_plan": null, "billing_state": null, "vat_id": null, "trial_ends_at": "2017-06-27 10:06:05", "last_read_announcements_at": "2017-06-27 10:06:05", "created_at": "2017-06-27 10:06:05", "updated_at": "2017-06-28 10:40:07", "tax_rate": 0 } }, "buildings": { "data": [ { "id": 4, "team_id": 1, "name": "Oasis", "created_at": "2017-06-30 13:15:30", "updated_at": "2017-06-30 13:15:30", "pivot": { "sending_id": 16, "building_id": 4 } } ] }, "messages": { "data": [ { "id": 316, "sending_id": 16, "recipient_id": 42, "provider_id": "0B0000006A1ABFEF", "info": null, "status": "delivered", "price": "0.07500000", "error_text": null, "created_at": "2017-07-21 15:42:08", "updated_at": "2017-07-21 15:42:21", "recipient": { "id": 42, "name": "John Doe", "email": "john@doe.co", "mobile": "198765456789", "types": [ "Inhabitant" ], "building_id": 4, "created_at": "2017-07-01 07:21:52", "updated_at": "2017-07-01 07:21:52", "deleted_at": null } } ] } }, ... }

But when I try to display recipient name like the following:

<tr v-for="sending in sendings"> <td>{{ sending.created_at | moment }}</td> <td><div style="width: 300px">{{ sending.text }}</div></td> <td> <div v-for="building in sending.buildings.data" v-if="sending.buildings.data"> {{ building.name }} </div> </td> <td> <ul> <li v-for="message in sending.messages.data" v-if="sending.messages.data"> {{ message.recipient.name }} </li> </ul> </td> </tr>

I get this error in console and no row is display at all: TypeError: Cannot read property 'name' of undefined

It's odd because displaying Building name works just fine, the only difference is recipient is one level deeper..

Any thoughts?

Categories: Software

Vue.js access value of key

Vuejs - Fri, 2017-07-21 17:34

Trying to access the value of the key with Vue.js which is new for me. I want to use the key as the id and access the title with key.title or something similar if possible. Here is the code I am trying:

HTML

<ul id="all"> <li v-for="(song,key) in songs" :class="{ active: song.isActive }" v-bind:id="key"> {{ key.title }} //Hound Dog </li> </ul>

Javascript

var vm = new Vue({ el: '#all', data: { songs: [ a:{ title:'Hound Dog', lyrics:'You aint nothing but a hound dog, crying all the time', isActive: true }, b:{ title:'Long Gone', lyrics:'I am long gone today', isActive: false } ] } })
Categories: Software

Variable availability to 'for' looped axios requests [duplicate]

Vuejs - Fri, 2017-07-21 17:30

This question already has an answer here:

I'm running an axios ajax call within a for object loop that is also within another axios ajax call. The parent object seems to be available within the the internal axios function, but specifying the object within the loop with [i] returns undefined. Here is my current code:

// GET NEXT PAGE OF POSTS axios.get(`https://rootdomain.co.uk/cms/index.php/wp-json/wp/v2/posts?offset=1&per_page=4&page` + this.currentPage) .then(function (response) { var additionalPosts = response.data // var additionalPostsThumbnails // SET FEATURED IMAGE AND THUMBNAIL KEY AND VALUE for (var i = 0; i < additionalPosts.length; i++) { const featuredImageAPI = 'https://rootdomain.co.uk/cms/index.php/wp-json/wp/v2/media/' + additionalPosts[i].featured_media axios.get(featuredImageAPI).then(response => { console.log(additionalPosts) console.log(additionalPosts[i]) }) } // REMOVE 'is-loading' CLASS TO BUTTON button.classList.remove('is-loading') })

So console.log(additionalPosts) is working, but console.log(additionalPosts[i]) is returning undefined. Any ways around this?

Once I can access the specific object the aim is to add another key and value to the individual objects.

Appreciate any help. Thanks!

Categories: Software

Assign dynamic array values to the canvajs graph data in vuejs2

Vuejs - Fri, 2017-07-21 16:57

I am trying to populate canvajs graph using random array value. I am using Veujs2 library to implement the template to display the graph data. Please find the below file which i have pasted with the code.

import {Line} from 'vue-chartjs' export default Line.extend({ created () { this.generateRandomArray() }, methods: { generateRandomArray: () => { var dataForX = Array.from({ length: 7 }, () => Math.floor(Math.random() * 40)) } }, mounted () { this.renderChart({ labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'Server One', backgroundColor: '#FC2525', // data: [40, 39, 10, 40, 39, 80, 40] data: this.dataForX }, { label: 'Server Two', backgroundColor: '#05CBE1', data: [60, 55, 32, 10, 2, 12, 53] } ] }, {responsive: true, maintainAspectRatio: false}) }

})

In generateRandomArray() i have the dataForX variable value, i am not able to use this variable inside the renderchart function.

Categories: Software

How can I run slider in vue component?

Vuejs - Fri, 2017-07-21 16:45

My view like this :

@foreach($leagues as $league) <a @click="$refs.leagues.changeLeague({{ $league->id }})"> {{ $league->name }} </a> @endforeach ... <top-league class="slick" league-id="{{ $league_id }}" ref="leagues"></top-league>

My top league component vue like this :

<template> <div class="row"> <div class="col-md-3" v-for="item in items"> <div class="panel panel-default"> <div class="panel-image"> <a :href="baseUrl+'/leagues/'+item.id+'/'+item.name" :style="{backgroundImage: 'url(' + baseUrl + '/img/leagues/'+item.photo+ ')'}"> </a> </div> </div> </div> </div> </template> <script> ... export default { ... props: ['leagueId'], created() { $('.slick').slick({slidesToShow: 3, infinite: false}); this.getTopLeague([{league_id: this.leagueId}]) // this is ajax if load first }, computed: { ...mapGetters([ 'getListLeague' ]), items() { const n = ['getListLeague'] return this[n[0]] // this is response ajax // exist 5 league } }, methods: { ...mapActions([ 'getTopLeague' ]), changeLeague(leagueId) { this.getTopLeague([{league_id: leagueId}]) // this is ajax if a link clicked } } } </script>

When loaded the first time, there are 5 items of data displayed in the form of sliders. I tried putting this code : $('.slick').slick({slidesToShow: 3, infinite: false}); in created, but there was an error

If the code executed, there exist error like this :

[Vue warn]: Error in created hook: "TypeError: $(...).slick is not a function"

How can I solve it?

Categories: Software

Import jquery plugin in Vue component

Vuejs - Fri, 2017-07-21 15:53

I'm trying to import an external jQuery plugin in a Vuejs component. The plugin is nested.js How can I do? Thanks

Categories: Software

Is there a way to server render components with Nuxt.js?

Vuejs - Fri, 2017-07-21 15:37

we are in a big project building a muti-user system imagine something like Wordpress or Blogger where every user has their own site on a subdomain e.g. john.ourcompany.com.

We used Vue.js without much trouble to build the admin. But for the frontend we would like to have server-side rendering (because of SEO reasons of course).

The trouble is our template looks like this (see below) and the idea is the user can choose what header/body/footer their site uses.

So the app makes an API Call to ask for the config of the site. When the config is returned the app now knows which component to use for header, footer and body. At this point it load only one header, one body, one footer.

Problem is Nuxt.js says it does server-side render things but it does not. It only renders the content of the page and none of the component content.

<template> <div> <!-- headers --> <header-alpha v-if="doneLoading && shopTheme.header == 'Header-alpha'"></header-alpha> <header-beta v-if="doneLoading && shopTheme.header == 'Header-beta'"></header-beta> <header-delta v-if="doneLoading && shopTheme.header == 'Header-delta'"></header-delta> <header-epsilon v-if="doneLoading && shopTheme.header == 'Header-epsilon'"></header-epsilon> <header-eta v-if="doneLoading && shopTheme.header == 'Header-eta'"></header-eta> <header-gamma v-if="doneLoading && shopTheme.header == 'Header-gamma'"></header-gamma> <header-zeta v-if="doneLoading && shopTheme.header == 'Header-zeta'"></header-zeta> <!-- home bodies --> <home-alpha v-if="doneLoading && shopTheme.homepageBody == 'Home-alpha'"></home-alpha> <home-beta v-if="doneLoading && shopTheme.homepageBody == 'Home-beta'"></home-beta> <home-delta v-if="doneLoading && shopTheme.homepageBody == 'Home-delta'"></home-delta> <home-epsilon v-if="doneLoading && shopTheme.homepageBody == 'Home-epsilon'"></home-epsilon> <home-eta v-if="doneLoading && shopTheme.homepageBody == 'Home-eta'"></home-eta> <home-gamma v-if="doneLoading && shopTheme.homepageBody == 'Home-gamma'"></home-gamma> <home-theta v-if="doneLoading && shopTheme.homepageBody == 'Home-theta'"></home-theta> <home-zeta v-if="doneLoading && shopTheme.homepageBody == 'Home-zeta'"></home-zeta> <!-- home footers --> <footer-alpha v-if="doneLoading && shopTheme.footer == 'Footer-alpha'"></footer-alpha> <footer-beta v-if="doneLoading && shopTheme.footer == 'Footer-beta'"></footer-beta> <footer-delta v-if="doneLoading && shopTheme.footer == 'Footer-delta'"></footer-delta> <footer-gamma v-if="doneLoading && shopTheme.footer == 'Footer-gamma'"></footer-gamma> </div>

<script> //some code that sets doneLoading and shopTheme vars </script>

IS there a way to make Nuxt.js render the components too?

Is there another way to server-side render the whole page before sending it to the user in the Vue.js universe?

If not we will pretty much have to abandon building the idea of building the whole frontend in Vue components and "downgrade" to something like Express/Pug templates + Vue components that load afterwards for the things that are not SEO-critical...

Categories: Software

Vue, how to invoke to data from component

Vuejs - Fri, 2017-07-21 14:49

I'm trying to do, delete a row from my Vue data: todos, but my method is in component. And the second problem is thaht I can't fix, how to do if my input is checked or not? My method toggle return or is checked or not, but I cannot set this on my template. Here is code:

Vue.component('todoList', { props: ['todoObj'], template: '<tr>' + '<td>{{todoObj.description}}</td>' + '<input type="checkbox" v-on:click="toggle"/>' + '<button v-on:click="deleteTodo">delete</button>' + '</tr>', methods: { toggle: function () { axios.post('/todo/toggleTodo', { 'todoId': this.todoObj.id }).then(function (response) { Here will be code... I have to set to my checbox or is checked or not. This response return "yes" or "no" }); }, deleteTodo: function () { axios.post('/todo/deleteTodo', { 'todoId': this.todoObj.id }).then(function (response) { console.log(response); <- here i don't know how to delete my row from table from Vue data: todos }); } } });

And here is my rest code:

var app = new Vue({ el: '#appTest', data: { todos: [], todoText: '' }, methods: { addTodo: function () { var self = this; axios.post('/todo/addTodo', { 'newTodo': this.todoText }).then(function (response) { console.log(response); self.todos.unshift({ 'id': response.data.id, 'description': response.data.description, 'done': response.data.done } ); self.todoText = ''; }).catch(function (error) { var errors = error.response.data.description[0]; console.log(errors); self.error = errors; }); }, toggle: function () { console.log('toggle?'); } }, created: function () { var self = this; axios.get('/todo').then(function (response) { console.log(response.data); self.todos = response.data; } ); } });
Categories: Software

How to get cell value when that cell is clicked?

Vuejs - Fri, 2017-07-21 14:49

When user clicks a table cell Vue should be aware of its value. In this case I am trying to set an event and pass the value.

Is there any way I could write this better, maybe from Vue itself - for example when the cell is clicked first get its content? I have many cells in table, and this doesn't work, it works only if I remove PHP part and try to write it manually - @click="calculate_price(10)

<?php foreach ($tr as $td) : ?> <td @click="calculate_price(<?php echo $td['price']; ?>)"> <?php echo $td['price']; ?> </td> <?php endforeach; ?> var app = new Vue({ el: '#app', data: { price: 0 }, methods: { calculate_price: function (price) { console.log(price); } } })

Vue version is 2.4.2

Categories: Software

Vue JS - Calculator - read output string as value

Vuejs - Fri, 2017-07-21 14:40

I'm building a calculator to test out my Vue JS skills. I have the fundamentals working or at least set-up, however if I enter more than one number (i.e. 34) I can't get it to read 34 as a whole value, rather it adds 3 and 4 to the total. The snippet I'm having trouble with is here:

press: function(num) { if(this.currentNum == 0) { this.currentNum = num; this.output = num.toString(); } else { this.output += num.toString(); this.currentNum = this.output.parseInt(); } },

Here's the whole thing on CodePen for better context - https://codepen.io/ajm90UK/pen/BZgZvV

I think this is more of a JS issue rather than anything specific to Vue but even with parseInt() on the string I'm having no luck. Any suggestions on how I can read the display (output) would be greatly appreciated, been at this for hours now!

Thanks!

Categories: Software

vuejs Incorrect component definition

Vuejs - Fri, 2017-07-21 14:07

I have two components - 'HelloIndex' and 'HelloShow'.

The problem is that when I try to do this

this.$router.push({name: 'HelloShow', params: {id: 1}})

, then the 'HelloIndex' component is loaded instead of 'HelloShow'. In my router:

import Vue from 'vue' import Router from 'vue-router' import HelloIndex from '@/components/HelloIndex' import HelloShow from '@/components/HelloShow' Vue.use(Router) export default new Router({ routes: [ { path: '/index', name: 'HelloIndex', component: HelloIndex, children: [ { path: ':id/show', name: 'HelloShow', component: HelloShow } ] } ] })

HelloIndex.vue:

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'helloIndex', data () { return { msg: 'INDEX' } } } </script>

HelloShow.vue:

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'helloShow', data () { return { msg: 'SHOW' } } } </script>

App.vue

<template> <div id="app"> <button @click="show">show</button> <router-view></router-view> </div> </template> <script> export default { name: 'app', methods: { show () { this.$router.push({name: 'HelloShow', params: {id: 1}}) } } } </script>

main.js

import Vue from 'vue' import App from './App' import router from './router' new Vue({ el: '#app', router, template: '<App/>', components: { App } })

What's wrong with the names of the components?

Categories: Software

Check if prop passed validation

Vuejs - Fri, 2017-07-21 12:51

I have the following component property (it's basically for a bootstrap alert component):

props: { alertType: { validator: function (value) { return [ "success", "info", "warning", "danger" ].indexOf(value) >= 0; }, default: "danger" }, // Some more things computed: { classes: { //Compute the correct classes for the alert type var classesObj ={ 'alert-dismissible': this.dismissable }; classesObj["alert-"+this.alertType]=true; //Problem if invalid return classesObj; } }

This works well in the sense that if I don't provide an alert type it uses "danger", however if I do provide an alert type and it does not pass validation then the alertType is set to that value and a console warning is emitted (which as I understand is the intended behaviour).

My question is whether it's possible within the classes computed property to determine whether the alertType prop passed or failed validation (and ideally if it failed get and use the default value, based on the component prop definition.

Categories: Software

Removing query string parameter from Url

Vuejs - Fri, 2017-07-21 11:52

Coming from AngularJS I thought this would be easy enough in Vue.js 2 as well. But it seems this is difficult by design in Vue.

In AngularJS I can do this $location.search('my_param', null); which will effectively turn https://mydomain.io/#/?my_param=872136 into https://mydomain.io/#/.

In Vue I have tried this.$router.replace('my_param',null);, but it will only do https://mydomain.io/#/?my_param=872136 -> https://mydomain.io/#/my_param, leaving the empty my_param.

Isn´t there anyway in Vuejs2 to remove the query params from the Url? Should I resort to plain JS to achieve this?

Categories: Software

Pages