Vuejs

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

Vue.JS failed to dynamically load template

Fri, 2017-08-04 13:29

I can't manage to build something similar to the vue.js example router application (https://github.com/chrisvfritz/vue-2.0-simple-routing-example).

I have removed every fancy stuff in order to make it work. But I still have the infamous error message on page load:

[Vue warn]: Failed to mount component: template or render function not defined. found in ---> <Anonymous> <Root>

I did nothing fancy, just trying to dynamically load a page:

// file: app/index.js import Vue from 'vue'; const app = new Vue({ el: "#app", data: { }, computed: { ViewComponent() { const matchingView = 'Home'; return require('./pages/' + matchingView + '.vue'); }, }, render(h) { return h(this.ViewComponent); }, });

And the page is only a static template:

// file app/pages/Home.vue <template> <p>Home Page</p> </template> <script> export default { }; </script>

What I don't understand is that I can make my page work if I statically import my page:

// file app/index.js import HomePage from './pages/Home.vue'; const app = new Vue({ // ... computed: { ViewComponent() { return HomePage; } } });

I suspect that I did not correctly configured my webpack build, but can't find out what is happening here... I have installed the vue-loader and vue-template-compiler as stated in the documentation, but it did not change anything.

Here are my dependencies:

"devDependencies": { "babel-core": "^6.25.0", "babel-loader": "^7.1.1", "babel-preset-es2015": "^6.24.1", "vue-loader": "^13.0.3", "vue-template-compiler": "^2.4.2", "webpack": "^3.4.1", "webpack-dev-server": "^2.6.1" }, "dependencies": { "vue": "^2.4.2" }

And the webpack.config.json file

var path = require('path'); module.exports = { entry: './app/index.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'aurora-designer.js', }, module: { rules: [ { test: /\.vue$/, use: { loader: 'vue-loader', }, }, { test: /\.test$/, exclude: '/node_modules/', use: { loader: 'babel-loader', }, }, ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', } }, devServer: { historyApiFallback: true, noInfo: true, }, };
Categories: Software

How to use the Async Component way to import component?

Fri, 2017-08-04 13:15

I have a question about Async Component.

I got a error message when try to import a component using Async Way.

Is it possible to do that or My concept totally wrong about using Async Component way ?

Failed to mount component: template or render function not defined.

My Dashboard Component

<template> <div> <logout></logout> </div> </template> <script> const logout = resolve => require(['./child/Logout'], resolve) export default { name: 'dashboard', components: { logout } } </script>

Logout Component

<template> <div class="view logout"> <el-button>Logout</el-button> </div> </template> <script> export default { name: 'logout' } </script>
Categories: Software

Vue js - Data from post request will not render

Fri, 2017-08-04 12:10

I have the next vue instance:

var immobles_destacats = ($('#immobles_destacats').length > 0) ? new Vue({ el: '#immobles_destacats', data: { immobles: {} }, methods: { add: function(i) { if (this.immobles[i].imatges.lenght == this.immobles[i].counter) { return this.immobles[i].counter = 0; } return this.immobles[i].counter++; }, substract: function(i) { if (this.immobles[i].counter == 0) { return this.immobles[i].counter = this.immobles[i].imatges.lenght; } return this.immobles[i].counter--; } }, mounted: function() { $.post('get_immobles_destacats', function(immobles, textStatus, xhr) { for (var i = 0; i < immobles.length; i++) { immobles_destacats.immobles[i] = immobles[i]; immobles_destacats.immobles[i].counter = 0; } }); } }) : null;

And the next html to render the data 'immobles':

<div id="immobles_destacats"> <div v-for="(immoble, key) in immobles" class="immoble"><img v-bind:src="immoble.imatges[immoble.counter].url"/> <input type="button" v-on:click="add(key)" value="+"/> <input type="button" v-on:click="substract(key)" value="-"/> </div> </div>

As you can see, I set the data 'immobles' in the mounted function and I get this: google chrome Vue DevTools extension on the loaded page The problem comes when the page is loaded nothing is rendered, is it because the data 'immobles' doesn't trigger "onchange-renderhtml" when it's filled in the post request? if so, how can I set this "onchange-renderhtml" to the data 'immobles'?

Categories: Software

Vue Js not updating DOM first time with updated array

Fri, 2017-08-04 12:05

I want to make a image preview when upload images. I could able to get the path of image in an array but the array not updates first time when i upload the image. When i click the DOM on vue-tool it updates the array but the image doesn't preview. I have itemsImages array. when i upload images the array should have updated immediately. But it doesnt update. If i click on DOM from vue-devtools the array updates. Here is my code:

html

<div class='row'> <div v-for="item in itemsImages">{{item}}</div> </div>

script

export default { data() { return { items: [], itemsAdded: '', itemsNames: [], itemsSizes: [], itemsImages: [], itemsTotalSize: '', formData: '', }, methods: { onChange(e) { this.successMsg = ''; this.errorMsg = ''; this.formData = new FormData(); let files = e.target.files || e.dataTransfer.files; this.itemsAdded = files.length; let fileSizes = 0; var vm = this; for (let x in files) { if (!isNaN(x)) { this.items = e.target.files[x] || e.dataTransfer.files[x]; this.itemsNames[x] = files[x].name; this.itemsSizes[x] = this.bytesToSize(files[x].size); fileSizes += files[x].size; var reader = new FileReader(); reader.onload = (event) => { vm.itemsImages[x] = event.target.result; }; reader.readAsDataURL(files[x]); this.formData.append('items[]', this.items); } } this.itemsTotalSize = this.bytesToSize(fileSizes); }, }, }

here is an screenshot: enter image description here

Categories: Software

Vue.js - best SEO solution for Infinite Scrollling

Fri, 2017-08-04 11:58

I am building a forum app using Laravel and Vue.js. Now I am using AJAX requests for infinite scrolling for both threads and commments. I am worried about SEO and thinking about possible solutions.

Essentially I would like to know if there is a good alternative to Server Side Rendering? Maybe something like building a quick and dirty SEO version of the website that shows up if you disable Javascript (would Google even crawl that?).

2nd question: If I were to use SSR, would it be possible to use SSR only for threads and comments and leave the rest on the client-side?

Categories: Software

How to write Vue js code in separate file and include in laravel

Fri, 2017-08-04 11:57

Please suggest me in this. How to write Vue js code in separate file and include in laravel Blade page code,

How do i write code in separate js file.

Am also using gulp file.

@section('js') <script> new Vue({ // Defining a element. el: '#branddashboard-html', data: { // Defining data variable. brandStats: null }, // On load functionality. created: function () { // Initializing method. this.getData(); }, }, // Methods to implement. methods: { getData: function () { self.brandStats = null; $.get('brand-stats/' + userId + '/' + period, function (data) { self.brandStats = data; }); } } }); </script> @endsection
Categories: Software

How to return boolean with axios

Fri, 2017-08-04 11:54

In VueJS I am trying to return a boolean with axios

allContactsSaved() { let promise = axios.get('/contacts'); console.log(promise.then(function (response) { response.data.data.forEach(function(contact) { if (!contact.saved) { return false; } }); return true; })); }

The console.log is just returning

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

Categories: Software

I can't set "disabled" parameter in Vue to be persistent

Fri, 2017-08-04 10:20

I can't set "disabled" parameter to be persistent. If I set disable: true inside data function, it seems that it doesn't do anything.

You can see inside mounted() that it calls checkCanVote() and in there at first the console.log says it is set to false, then I set it to true but on stars hover (star_over()) it is again false?

http://jsfiddle.net/7unqk49k/1/

Template

<div id="star-app" v-cloak class="col-md-4"> <star-rating value="<?php echo $this->rating_rounded; ?>"></star-rating> </div> <template id="template-star-rating"> <div class="star-rating"> <label class="star-rating__star" v-for="rating in ratings" :class="{'is-selected': ((value >= rating) && value != null), 'is-disabled': disabled}" @mouseover="star_over(rating)" @mouseout="star_out"> <input class="star-rating star-rating__checkbox" type="radio" :name="name" :disabled="disabled" :id="id" :required="required" v-model="value" @click="set(rating)"> ★ </label> </div> </template>

JS

Vue.component('star-rating', { template: '#template-star-rating', data: function data() { return { value: null, temp_value: null, ratings: [1, 2, 3, 4, 5], disabled: true }; }, props: { 'name': String, 'value': null, 'id': String, 'disabled': Boolean, 'required': Boolean }, methods: { star_over: function star_over(index) { console.log(this.disabled); if (this.disabled == true) { return; } this.temp_value = this.value; this.value = index; }, star_out: function star_out() { if (this.disabled == true) { return; } this.value = this.temp_value; }, set: function set(value) { if (this.disabled == true) { return; } this.temp_value = value; this.value = value; // On click disable - this works this.disabled = true; }, checkCanVote: function() { console.log('Inside checkCanVote'); console.log(this.disabled); this.disabled = true; console.log(this.disabled); } }, mounted() { this.checkCanVote(); } }); new Vue({ el: '#star-app' });
Categories: Software

vue js with vue router and lazy loading custom tags/components

Fri, 2017-08-04 09:57

I'd like to have Vue custom components loaded only after the route has been clicked.

Let's say my app's stripped down html structure looks like this:

<div id="admin"> <admin-menu><!-- component with routes --></admin-menu> <div id="content-container"> <!-- want dynamically loaded Single Page Components here --> </div> </div>

I'd like content container to be the target, where the dynamically loaded Single Page Components should be placed.

The one thing I don't want is to predefine the custom components in the content container right from the start like this:

<div id="admin"> <admin-menu><!-- component with routes --></admin-menu> <div id="content-container"> <my-component-1></my-component-1> <my-component-2></my-component-2> <my-component-3></my-component-3> <my-component-N></my-component-N> </div> </div>

If I do that, they must be registered i.e. loaded when vue hits them on startup of the app and but I'd like the components to be lazy loading.

So how can I initialize and place a single file component in the target content-container only after the respective router link has been clicked?

Categories: Software

Load nested JSON array into select in Vue using computed function

Fri, 2017-08-04 09:54

Originally in my Vue component I had a series of nested if statements that would go through the JSON data to determine whether a text input should be displayed or a select based on a has_selectable_value option being true (select display) or false (text input display), and if it was a select then loop through the data and output associated options.

I have been able to change that to a computed statement which almost does everything I need it to do apart from one little thing which is to display the select options.

Here is the relevant part of the Vue Code:

<template v-else-if="searchtype == 9"> <select v-for="service in selectableServices" class="form-control" v-model="searchvalue" required> <option value="">Select A Location</option> <option v-for="sl in selectableLocations" :value="sl.location_id">{{sl.name}}</option> </select> <input v-for="service in nonSelectableServices" class="form-control" v-model="searchvalue" placeholder="Enter Search Value" required> </template>

The current computed functions:

services: function () { var ret = [] this.countries.forEach(function(country) { country.states.forEach(function(state) { state.services.forEach(function(service) { ret.push(service) }); }); }); return ret; }, selectableServices: function () { return this.services.filter(service => service.id == this.service && service.has_selectable_location); }, nonSelectableServices: function () { return this.services.filter(service => service.id == this.service && !service.has_selectable_location); }, selectableLocations: function () { // Filter one more level down return this.selectableServices.map(service => service.selectablelocations); },

This is the JSON data structure I am working with as well (I cut it back to the relevant parts for this part of the code):

[ { "id": 1, "name": "Country Name", "states": [ { "id": 1, "name": "State Name", "services": [ { "id": 1, "name": "Service Name", "has_selectable_location": 1, "selectablelocations": [ { "id": 1, "name": "Selectable Location A", }, ] } ] } ] } ]

Using a Vue plugin for Chrome I can see that the computed function selectableLocations loads an array containing the individual locations, but the existing v-for statement isn't able to function correctly. Instead I still need to go down one more level which I can do by adding an extra v-for loop like so:

<template v-for="selectableLocationsList in selectableLocations" > <option v-for="sl in selectableLocationsList" :value="sl.location_id">{{sl.name}}</option> </template>

Everything displays correctly, but I am not sure if this is best practice as I was hoping to do as much of this in a computed function as possible and ideally only require a single v-for statement. But if it's not possible like that I understand and I can leave it as is.

Thank you in advance.

Categories: Software

Conventions project with PHP and VueJs?

Fri, 2017-08-04 09:40

Basically I don't know how to start implementing VueJs into my project. Should I use a CDN or require it via NPM? NPM would make it easier to implement VueJs packages.

I have in (my own framework (for learning)) a path /public/ in which a index.php file is located, along with an assets folder (which leads is followed css/js folders).

So the question is, what would you recommend, and how would you implement routing etc.?

Categories: Software

Vue.js static hosted single-page app

Fri, 2017-08-04 09:34

I would like to use vue.js, and compile everything to a static site on Amazon S3. This seems to be possible with Nuxt, but it seems to generate separate HTML files for your routes. Is it not possible to generate a single-page static app with vue.js?

Categories: Software

How to load scss in vue.js

Fri, 2017-08-04 08:07

//Vuejs component

<template> <form class="form form--login" v-on:submit.prevent="login"> <h2 class="form__title">Login</h2> <div class="info info--error" v-if="infoError">Login failed. Please try again.</div> <div :class="{'is-waiting': loader}"> <div class="form-block"> <input v-model.trim="username" class="field" name="username" type="text" placeholder="User ID" required> </div> <div class="form-block"> <input v-model.trim="password" class="field" name="password" type="password" placeholder="Password" required> </div> <div class="form-block form__actions"> <router-link to="/password-reset">Lost your password?</router-link> <button class="button button--green form__submit">Login</button> </div> </div> </form> </template> <script> <style lang="scss" type="text/scss"> .is-waiting { position: relative; transition-duration: .3s; > * { opacity: .25; } &:before { content: ''; height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 9; } &:after { background: { position: center; size: cover; } content: ''; height: 64px; left: 50%; position: absolute; top: 50%; transform: translate(-50%, -50%); width: 64px; } } </style>

//webpack.config

"dependencies": { "onsenui": "^2.5.1", "node-sass": "^4.5.0", "sass-loader": "^5.0.1", "vue": "^2.4.2", "vue-onsenui": "^2.1.0", "vue-resource": "^1.3.4", "vuex": "^2.3.1" },

My component still doesn't load style correctly.

Please help!!

Categories: Software

Use VueProgress in Store.js

Fri, 2017-08-04 07:41
import VueProgressBar from 'vue-progressbar' Vue.use(VueProgressBar, { color: 'rgb(143, 255, 199)', failedColor: 'red', height: '2px' })

I have imported it and initialized it in my store.js(vuex) file.

Why Can't i use it for a function in store that requests a http.

Error -> Cannot read property 'start' of undefined

function something(state){ Vue.Progress.start(); Vue.http.get('https://something.com/abc.json') .then(response=>{ Vue.Progress.finish(); return response.json(); },response=>{ Vue.Progress.fail() }) .then(route=>{ console.log(route); }) }

How can i use it in my store.js

I can perfectly use it in my .vue components by -> this.$Progress.start() & <vue-progress-bar></vue-progress-bar> in template ,

for here , i am placing <vue-progress-bar></vue-progress-bar> in App.vue(main-component)

Categories: Software

view progress to http.get() query (by vue-resource) from firebase

Fri, 2017-08-04 03:05
this.$http.get('cities_&_stops/' + this.search_city_name[0].toUpperCase() + '.json' ) .then(response => { this.cities_array = []; return response.json(); }) .then(cities => { //console.log("cities from db -> "+cities); for(let city in cities){ this.city_object = { name : cities[city].toUpperCase(), class : '' } //console.log("pushing in array -> " + this.city_object.name); this.cities_array.push(this.city_object); //console.log("in city array -> " + this.city_object.name); } //console.log("what is in city array? -> " + this.cities_array); this.search_feature(); })

This is my query by http.get() method (using vue-resouce) from firebase database.

How can i see my progress in console(in %).

Categories: Software

Triggering child method (or computed property) from root - vue2

Fri, 2017-08-04 03:05

In nested object, my computed property in my component doesn't track changes well, so computed property doesn't get triggered as expected. Instead, I want to trigger it in the from parent.

What is the proper way of executing a method, preferably this computed method from my root?

I tried using

this.$emit('updated'); on root method

this.$parent.$on('updated', this.organise); and catch it like this,

but this returns me an error:

Error in event handler for "updated": "TypeError: Cannot read property 'apply' of undefined"

Categories: Software

How to add a div id to each element in a v-for list?

Fri, 2017-08-04 02:27

Here is my Vue

<div class="drag"> <h2>List 1 Draggable</h2> <ul> <li v-for="category in data"> <draggable v-bind:id="category" v-model="category" :move="checkMove" class="dragArea" :options="{group:'items'}"> <div v-for="item in category" style="border: 3px;">${ item.name }</div> </draggable> </li> </ul> </div> </div> <script> var vm = new Vue({ el: "#main", delimiters:['${', '}'], data: {{ data | tojson | safe }}, methods:{ checkMove: function(evt){ return true } } });

I want each of the div in my v-for to have an id. Based on this; https://vuejs.org/v2/guide/list.html

I think I need something like v-bind:key="category.id" in the li tag (the one with the v-for. That makes my div id [Object object][Object object][Object object].

I think this is for each of the items in my category. I would like to add a div id to each category as well as a div id to each item in category. These should be something like "category.name" (the name of the category, so uncategorized, and "item.name" in the item itself. My data object looks like this:

{"data": {"uncategorized": [{"id": 0, "name": ""}, {"id": 1, "name": "first"}, {"id": 2, "name": "another"}]}}

Categories: Software

How to pick v-model for Vue.js draggable when using a nested list

Fri, 2017-08-04 01:38

Here is my Vue

<div id="main"> <h1>Vue Dragable For</h1> <div class="drag"> <h2>List 1 Draggable</h2> <ul> <li v-for="category in data"> <draggable id="category" v-model="category" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="item in category" style="border: 3px;">${ item.name }</div> </draggable> </li> </ul> </div> </div> <script> var vm = new Vue({ el: "#main", delimiters:['${', '}'], data: {{ data | tojson | safe }}, methods:{ checkMove: function(evt){ console.log(evt.draggedContext.index); console.log(evt.draggedContext.futureIndex); console.log(evt.from.id); console.log(evt.to.id); axios.post('/categorize', { 'index': JSON.stringify(evt.draggedContext.index), 'futureIndex': JSON.stringify(evt.draggedContext.futureIndex), 'from':evt.to.id, 'to':evt.from.id, }); return true } } }); </script>

the data rendered in the template {{ data | tojson | safe }} just looks like:

{"data": {"uncategorized": [{"name": ""}, {"name": "first"}, {"name": "another"}]}}

Right now I am getting this error

You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.

so I don't think it it likes how I am using v-model. I am basing my code on this example: https://jsfiddle.net/dede89/32ao2rpm/ which uses raw son names in its v-model tags, but I cannot do that. So how should I do this? Thanks!

Categories: Software

VueJS: Uncaught SyntaxError: Unexpected token import

Fri, 2017-08-04 01:33

thanks for reading this. I am building a web app using vuejs and flask as server. Do you guys have any recommendation for why it does not recognize "import"? im trying to use this.$http.get . why it is not recognizing it? thanks in advance

import Vue from 'vue' import VueResource from 'vue-resource' Vue.component( 'button-labels', { props : ['labelbtn'], template : `<div class="button-container"><button class="button-app" v-for="label in labelbtn" v-on:click="clickHandler(label)" >{{label.label}}</button></div>`, methods : { clickHandler : function(label) { if (label.id === 1) { this.$emit('event_child', 'search-template') } }, } }) Vue.component( 'search-template', { props: ['searchdata'], data : { entries : [] }, template : `<div><input class="searchBar"><div class="response-list"><button class="entries"></button></div> <audio class="audio" controls></audio><button class="button-back" v-on:click="backHandler"> Return</button></div>` , methods : { backHandler : function(){ this.$emit('event_child', 'button-labels'); }, }, created : function(){ this.$http.get('https://google.com', (data) => { console.log( data ); }) .error((err) => console.log(err)) }, }) new Vue({ el: '#app', data : { labels : [ { id : 1, label : "Search" } , { id : 2, label: "Categories" }, { id : 3, label: "Favorites" }, {id : 4, label: "Settings"} ], currentView : "button-labels", }, methods : { eventChild : function(label) { this.currentView = label; } } })

this is my package.json

{ "scripts": { "transpile-es2015": "babel src -d lib" }, "devDependencies": { "babel-core": "^6.1.2", "babel-loader": "^6.1.0", "babel-plugin-transform-runtime": "^6.1.2", "babel-preset-es2015": "^6.1.2", "babel-runtime": "^6.0.14", "css-loader": "^0.21.0", "style-loader": "^0.13.0", "vue-hot-reload-api": "^1.2.1", "vue-html-loader": "^1.0.0", "vue-loader": "^7.0.1", "webpack": "^1.12.3", "webpack-dev-server": "^1.12.1" }, "dependencies": { "bootstrap": "^3.3.5", "vue-resource": "^0.1.17", "vue-router": "^0.7.5", "vue": "^1.0.7" } }

Categories: Software

Watching changes on an object in vue

Fri, 2017-08-04 00:59

I have a object named accounts and it hold information in this structure:

{ 1: { 'x': [ [], [], [] ], 'y': [ [], [] ], }, 2: { 'x': [ [], [] ], 'z': [ [] ], }, }

In my root, in data, it is stored.

Now I want to create another variable, watching this variable, and when new elements added or removed from this accounts variable, change my new variable and put it in the right format. This is how I want it to be:

{ 1: { 'x': [ [] ], 'y': [ [] ] }, 2: { 'y': [ [] ], 'z': [ [] ] } }

And when the letter level is added or removed, I want to add/remove from this watcher variable too.

new Vue({ el: '#root', data: { accounts: {}, watcher: {} }, methods: { changeHappened() { // values appended to accounts / changes applied // now how does the watcher object gets the wanted structure // and add/remove if new items added/removed } } })

Where is the best place to add this watcher and watch modifications on accounts object?

Categories: Software

Pages