Software
how to write global router-function in nuxt.js
I am using Vue.js with Nuxt.js, but I got a problem in router's functions.
In the pure Vue, i can write in main.js like this:
val route = new Router({ routes:{ [...] } }) route.beforeEach(to,from,next){ //do something to validate }And how to do the same in nuxt.js ? I can not find any file like main.js.
Also, all i know is to deal with the pages folder to achieve router, I can not set the redirect path
please help, thx :)
What should be on 'this' on 'destroyed' hook for VueJS Component?
I am working on a medium-sized app and notice a lot of memory increase when moving back and forth between components.
I put this on the component:
destroyed(){ console.log(this }I was surprised to find a lot - if not all - the 'data' still there plus computed properties. I thought this was supposed to be clean at that point. What all should be expected to be destroyed by that point? Is this a cause for concern and a potential source of memory leaks?
mysql stored value displayed as raw html in vue through php
I have a value stored as < b > supposed to be bold < /b > in mysql.
while fetching through php I used nearly all html entity related functions but no avail
//will be returned as json for vue $item ['value'] = $fetched_data;in vue template I use like this
{{$value}}and it gives me as html tags where I am supposed to print the bolded text, anything should I do in PHP or Vue to make this happen?
vuex "store" vs "data: store" in Vue() constructor, which is best?
Vue docs mention to use "data" option on constructor, to keep global/shared data: https://vuejs.org/v2/guide/state-management.html
This makes sense.
Vuex docs passes the "store" object, without a property name though: https://github.com/vuejs/vuex/blob/dev/examples/counter/app.js
new Vue({ el: '#app', store, render: h => h(Counter) })Shouldn't that have been
new Vue({ el: '#app', data: store, render: h => h(Counter) })?
Other examples pass it as "store: store" https://ypereirareis.github.io/blog/2017/04/25/vuejs-two-way-data-binding-state-management-vuex-strict-mode/
but "store" isn't a documented property: https://vuejs.org/v2/api/
How to retrieve data from vue component in another component?
There is a vue royter
..... const Edit = Vue.component('edit', require('./components/pages/edit.vue')); const Product_category = Vue.component('home', require('./components/pages/product_categories.vue')); const routes = [ ........ { path: '/product_categories', name: 'product_categories', component: Product_category }, { path: '/product_categories/edit/:id', name: 'product_categories_edit', components: {default: Edit, entity: Product_category}, props: {default: true, entity: true} } ];How can I get data in component Product_category componate Edit?
<script> export default { props: ['id', 'entity'], mounted: function () { console.log('Admin edit page mounted.'); console.log(this.entity); // Eror console.log(entity); // Eror this.getData(); }, } </script>A direct appeal is not suitable, because each router will have its own entity.
multiple $http.get calls must update row as they come
I have a table that holds information from multiple sources (websites). Each row is a different source. The user can refresh the data for each individual row/source/website by clicking a refresh icon, or, the user can update ALL rows by clicking the refresh icon in the header row.
I would like to have each row update as the data comes when the user clicks on the refresh ALL icon in the header row.
This actually works fine, but the table does not update until all requests are finished. I would like it to update as they come. There's a cool bounce animation when the data changes, so, it would look really great if each row would come in as the data arrives. I had it working once by fluke (rows updating at random when ajax call is done) but I lost that day of coding (thanks to my github poor practices)
Anyway, here's how I structured things currently. It does update the table but only when every single row is complete.
So it basically does the $http.get call for all websites, then it does the .then for all websites...I would rather each call process through to .then when it's finished (oh yeah, I can see ther esponse in the console but it still waits for all of them before sequentially going on to .then foreach one) here's relevant code.
vuejs laravel spark (which uses $http.get) laravel 5.3.31
...
Vue.component('websites', { // props: [''], /** * The components data */ data() { return { userLbProfiles: [], spin_icon_many: false, showRefreshButton: '', refreshTime: '', busy: '', changeStatus: '', }; }, /** * Bootstrap the component . */ mounted() { var self = this; this.fetchLastRefreshTime(); this.getData(); this.busy = false; this.showRefreshButton = true; }, /** * Component's methods */ methods: { /** * get current stored data from the DB * * @return response */ getData() { this.changeStatus = true; this.$http.get('/get/all/userLbProfiles') .then(function (response) { console.log(response); this.userLbProfiles = response.data; this.busy = false; this.spin_icon_many = false; this.changeStatus = false; }) }, /** * get only ONE row from the DB * * @return response */ getDataForOne(userLbProfileId, i) { this.changeStatus = true; this.$http.get('/get/one/userLbProfile/'+userLbProfileId) .then(function (response) { console.log(response); this.userLbProfiles[i] = response.data; console.log(this.userLbProfiles[i]+'number: '+i); this.busy = false; this.userLbProfiles[i].spin_icon = false; this.changeStatus = false; }) }, /** * Call the api to log into one website and fetch the live data * */ refreshOne(userLbProfileId,i) { this.userLbProfiles[i].spin_icon= true; this.busy = true; this.$http.get('/get/refresh/one'+userLbProfileId) .then(function (response) { console.log(response); this.getDataForOne(userLbProfileId,i); // this.getData(); }) }, /** * Call the api to log into and update the specified # of websites * next in the list * */ refreshMany() { this.spin_icon_many = true; this.busy = true; for(i=0; i <= this.userLbProfiles.length-83; i++) { this.userLbProfiles[i].spin_icon= true; this.$http.get('/get/refresh/many'+this.userLbProfiles[i].id) .then(function (response) { console.log('got response after fetching refresh data for: '+this.userLbProfiles[i].id); console.log(response); }); } }, <get-website-data inline-template> <div class="panel panel-default"> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" role="form"> <table class="table table-hover"> <tr> <th>Data Item 1</th> <th>Data Item 2</th> <th> <form> <a href="" @click.prevent="refreshMany()"> <i v-if="spin_icon_many" class="fa fa-fw fa-refresh fa-spin fa-2x"> </i> <i v-else class="fa fa-fw fa-refresh fa-2x"> </i> </a> </form> --> <i class="fa fa-fw fa-refresh fa-2x"> </th> <th>Last Update</th> </tr> <tr v-for="(userLbProfile, index) in userLbProfiles"> <td> @{{ dataItem1 }} </td> <td> @{{ dataItem2 }} </td> etc..
What happens with this code is that (obviously) the for loop runs out before I get any response, so the behaviour is
If there's 10 websites, let's say, 10 ajax calls go out but the first .then doesn't process until ALL 10 are finished, even if I can see the response in the console.. it just waits for all the others. I would think .then would process individual for that response, but somehow they all know about each other? Probably the for loop?
Anyway, then getData runs 10 times and all the data is loaded in the table.... 10 times... the last call's data is what sticks obv.
I tried experimenting with isolating code into functions, thinking that might make each asynch call independent somehow (I think that s how I got to fluke work that one time) but no luck.
I also tried calling getDataForOne thinking it might update the row and trick it into updating right away, but I didn't get vue to recognize the data changed (maybe this is the right route to take?)
It would be really difficult to return the data within the same call because of the multi-step process used to get the live data from the website. It almost has to be a separate call to the DB (almost)
Any help is greatly appreciated this has been an ongoing issue for weeks now.
How to maintain a VueJS app and how to update it on live server?
I have a general question to which I can not find an answer. I am new to Javascript apps and frameworks. Let's say that you have a website that is live and running, then when you need to fix bugs or make improvements you can connect to FTP get the files you need to change and upload them back. What about VueJs framework, Angularjs etc., if it must be "built" (compiled) before you can use it on a live server (ex. Apache), how do you maintain such project?
Vue.JS failed to dynamically load template
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, }, };How to use the Async Component way to import component?
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>Vue js - Data from post request will not render
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:
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'?
Vue Js not updating DOM first time with updated array
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); }, }, }Vue.js - best SEO solution for Infinite Scrollling
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?
How to write Vue js code in separate file and include in laravel
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> @endsectionHow to return boolean with axios
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}
I can't set "disabled" parameter in Vue to be persistent
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' });vue js with vue router and lazy loading custom tags/components
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?
Load nested JSON array into select in Vue using computed function
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.
Conventions project with PHP and VueJs?
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.?
Vue.js static hosted single-page app
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?
How to load scss in vue.js
//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!!