link1233 link1234 link1235 link1236 link1237 link1238 link1239 link1240 link1241 link1242 link1243 link1244 link1245 link1246 link1247 link1248 link1249 link1250 link1251 link1252 link1253 link1254 link1255 link1256 link1257 link1258 link1259 link1260 link1261 link1262 link1263 link1264 link1265 link1266 link1267 link1268 link1269 link1270 link1271 link1272 link1273 link1274 link1275 link1276 link1277 link1278 link1279 link1280 link1281 link1282 link1283 link1284 link1285 link1286 link1287 link1288 link1289 link1290 link1291 link1292 link1293 link1294 link1295 link1296 link1297 link1298 link1299 link1300 link1301 link1302 link1303 link1304 link1305 link1306 link1307 link1308 link1309 link1310 link1311 link1312 link1313 link1314 link1315 link1316 link1317 link1318 link1319 link1320 link1321 link1322 link1323 link1324 link1325 link1326 link1327 link1328 link1329 link1330 link1331 link1332 link1333 link1334 link1335 link1336 link1337 link1338 link1339 link1340 link1341 link1342 link1343 link1344 link1345 link1346 link1347 link1348 link1349 link1350 link1351 link1352 link1353 link1354 link1355 link1356 link1357 link1358 link1359 link1360 link1361 link1362 link1363 link1364 link1365 link1366 link1367 link1368 link1369

[Vue.js] How to auto refresh a computed property at axios in vuejs

I’m calling restapi data with axios in vuejs , this data to be auto refreshed everysecond to see any change in numbers. I can see data, its working but refresh is not working

I’ve put setinterval function in methods area but it doesnt refresh any data.

import axios from ‘axios’;
export default {
data () {
return {
btctrk: null,
bnnc: null,
}
},
computed: {
result1: function(){
return this.btctrk[0].ask / this.btctrk[4].bid;
},
result2: function(){
return this.btctrk[0].bid / this.btctrk[4].ask;
},
result3: function(){
return (1-(this.bnnc[11].bidPrice / this.result1))*100;
},
result4: function(){
return (1-(this.result2 / this.bnnc[11].askPrice))*100;
},
},
mounted () {
axios
.get(‘https://www.api1.com/api/ticker')
.then(response => (this.btctrk = response.data))
.catch(error => console.log(error))
axios
.get(‘https://api.api2.com/api/v3/ticker/bookTicker')
.then(response => (this.bnnc = response.data))
.catch(error => console.log(error))
},
methods: {
startInterval: function () {
setInterval(() => {
this.result1;
this.result2;
this.result3;
this.result4;
}, 1000);
}
}
}

Solution :

Computed properties are only re-evaluated if some of its dependencies have changed, meaning that they have some sort of “cache” if we can put it like that. See: Computed caching vs Methods

Another thing is that you are running the Axios get call when mounted(), meaning that the call is only running once the component is mounted and not refreshing at all. See: Lifecycle Diagram

My solution to the problem will be something like this:

export default {
data () {
return {
btctrk: null,
bnnc: null,
}
},
computed: {
result1: function(){
return this.btctrk[0].ask / this.btctrk[4].bid;
},
result2: function(){
return this.btctrk[0].bid / this.btctrk[4].ask;
},
result3: function(){
return (1-(this.bnnc[11].bidPrice / this.result1))*100;
},
result4: function(){
return (1-(this.result2 / this.bnnc[11].askPrice))*100;
},
},
methods: {
btcTrkAPICall: function () {
axios
.get(‘https://www.api1.com/api/ticker')
.then(response => (this.btctrk = response.data))
.catch(error => console.log(error))
},
bnncAPICall: function () {
axios
.get(‘https://api.api2.com/api/v3/ticker/bookTicker')
.then(response => (this.bnnc = response.data))
.catch(error => console.log(error))
},
intervalFetchData: function () {
setInterval(() => {
this.btcTrkAPICall();
this.bnncAPICall();
}, 1000);
}
},
mounted () {
// Run the functions once when mounted
this.btcTrkAPICall();
this.bnncAPICall();
// Run the intervalFetchData function once to set the interval time for later refresh
this.intervalFetchData();
}
}

I think this is a plausible solution, feel free to test it out.

[Vue.js] return validation errors from laravel controller to vue

everybody, I need to return error validation for this validation code to vue.js

Validator::make($request->all(), [
‘title’ => ‘required|unique:posts|max:255’,
‘body’ => ‘required’,
])->validate();

there is tried

$validator = Validator::make($request->all(), [
‘title’ => ‘required|unique:posts|max:255’,
‘body’ => ‘required’,
])->validate();

if ($validator->fails()) {
return $this->sendError(‘error validation’, $validator->errors());
}

but did’t work for me

Solution :

List errors

$validator->messages();

[Vue.js] Vuejs + webpack - build for production but deploy to localhost

Trying to figure out how can I create a production build with webpack but first run it locally as a last test before deploying it to the server.

I was thinking of creating another command something like npm run build_local for that purpose but can’t quite figure out how to do that.

I can see the following in the root package.json and I was thinking of somehow combining dev + build but can’t figure out how to do that (or using config otherwise):

“scripts”: {
“dev”: “webpack-dev-server –inline –progress –config build/webpack.dev.conf.js”,
“start”: “npm run dev”,
“lint”: “eslint –ext .js,.vue.js src”,
“build”: “node build/build.js”
},

Any advice on how can I run a production build in localhost with something like npm run build_local command?

EDIT

What I’ve tried so far is to run (manually) http-server ./dist which seem to run the folder on localhost, but the result in fact deviates from production (and dev) behavior - in my case it first renders everything as expected but as long as I press refresh, it returns 404 not found which is unexpected (on dev and server deployed versions it still renders the login page in this case):

for example if I open localhost:8080, vue.js redirects me to localhost:8080/login which is expected and works fine. On refresh it gives 404 though.

Ideally I’d expect it to work at least in the same way as dev build on localhost.

Any ideas?

Solution :

So it was as simple as combining the dev command and providing prod config to it under the root package.json:

“build_local”: “webpack-dev-server –inline –progress –config build/webpack.prod.conf.js”
//

Or in the package.json:

“scripts”: {
“dev”: “webpack-dev-server –inline –progress –config build/webpack.dev.conf.js”,
“start”: “npm run dev”,
“lint”: “eslint –ext .js,.vue.js src”,
“build”: “node build/build.js”
“build_local”: “webpack-dev-server –inline –progress –config build/webpack.prod.conf.js”
}

Now I can do npm run build_local which runs production build on localhost

Note: as per this github thread and this doc reference to prevent 404 on refresh also add the following to the webpack.prod.conf.js (anywhere in the file, but for reference you can paste it just before plugins)

devServer: {
contentBase: path.join(__dirname, ‘dist’),
historyApiFallback: true, //this line is requried
compress: true,
port: 9000
},

You can now check the production build under the localhost:9000

If anyone knows about any drawbacks give me a comment or post the corrected answer

[Vue.js] Check if user scrolled to bottom

I need show button backtotop only if user has scrolled bottom > 250. How I can do it?

My code:

<template>
<div>
<button v-if=”checkScroll” class=”goTop” @click=”backToTop”>
<i class=”fa fa-angle-up” aria-hidden=”true”></i>
</button>
</div>
</template>

<script>
export default {
methods: {
computed: {
checkScroll() {
if ($(document).scrollTop() > 250) {
return true;
} else {
return false;
}
}
},
backToTop() {
this.$scrollTo(‘html’);
},
}
}
</script>

My code is not working. Errors I do not get. Button is hidden.

Solution :

Also don’t forget to destroy the event:

new Vue({
el: “#app”,
data() {
return {
scroll: null
}
},
methods: {
handleScroll(e) {
this.scroll = window.scrollY || window.scrollTop
}
},
created() {
window.addEventListener(‘scroll’, this.handleScroll);
},
destroyed() {
window.removeEventListener(‘scroll’, this.handleScroll);
}
})
html {
height: 3000px; /* some random height for demonstration purpose */
}

button {
position: fixed;
}
<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.2/dist/vue.js"></script>

<!– scroll to see the button –>

<div id=”app”>
<button v-show=”scroll > 250”>foobar</button>
</div>

Solution 2:

Use the onScroll event in Javascript to detect when the user scrolls down/up and use scrollTop() to automatically move to the top of the page when the button is clicked.

Make sure it is position:fixed;.

For more info, check out these:
onScroll
scrollTop()

To show/hide the button just change it’s size using HTML DOM methods. For example:

document.getElementsByClassName(“goTop”)[0].width = 30;

Solution 3:

codepen.io has great sketches for in demand features like this all for free. here is a scroll to top functionality page you can tweak to fit the needs hopefully https://codepen.io/rolandtoth/pen/eMamVK

.scrolltop-wrap {
$size: 3rem;
$offsetBottom: 2rem;
$offsetHorizontal: 2rem;
$scrollToRevealDistance: 12rem; // scroll offset to reveal scroll-to-top link

It’s all scss instead of javascript. Here is a scss to css generator you can use, https://www.cssportal.com/scss-to-css/

[Vue.js] How can I use dynamic components in a ListView

when trying to populate a NativeScript-vue.js ListView with templates that contain components of which their types are not known ahead of time. For example, this code does not work as NativeScript does not have a ‘component’ element but this suggests what when trying to accomplish:

<ListView for=”component in components”>
<v-template>
<component :is=”component” />
</v-template>
</ListView>

computed: {
components () {
return [‘Label’, ‘Button’];
}
}

Yes, I know you can use if=”” in a v-template, but in this case I do not know ahead of time what components need to be loaded in the ListView. In my case when loading global components in a plugin, and these components will be referenced in the ListView.

Solution :

the template can not be dynamic, that’s the whole point of using ListView - keeping them static, so they can be reused as needed. If you like to see different components based on data then you must use multiple templates.

Read more on docs.

Solution 2:

Thanks @Manoj. Those wise words made me think, the template can’t be dynamic but the contents of the v-template can be. Maybe not for everyone, but this code works for me:

// App.vue

<template>
<Page>
<ActionBar title=”Welcome to NativeScript-Vue!”/>
<GridLayout columns=”*“ rows=”400,*“>
<ListView ref=”lv” for=”item in items”>
<v-template>
<v-component :type=”item.type” :options=”item.options” />
</v-template>
</ListView>
</GridLayout>
</Page>
</template>

<script lang=”ts”>
import vue.js from ‘nativescript-vue’
import { Component } from ‘vue-property-decorator’
import VComponent from ‘./VComponent.vue’

@Component({
components: {
VComponent
}
})
export default class App extends vue.js {
get items () {
return [
{type: ‘Label’, options: [{key: ‘text’, value: ‘when a Label’}, {key: ‘color’, value:’red’}] },
{type: ‘Button’, options: [{key: ‘text’, value:’when a Button!’}]}
]
}
}
</script>

// VComponent.vue

<template>
<StackLayout ref=”myLayout”>
</StackLayout>
</template>

<script lang=”ts”>
import vue.js from ‘nativescript-vue’
import { Component, Prop } from ‘vue-property-decorator’
import { StackLayout } from ‘tns-core-modules/ui/layouts/stack-layout’
import { Label } from ‘tns-core-modules/ui/label’
import { Button } from ‘tns-core-modules/ui/button’

const classByClassName = {
‘Label’: Label,
‘Button’: Button
}

@Component
export default class CoolTemplate extends vue.js {
@Prop() type!: string;
@Prop() options;

mounted () {
if (this.type) {
const myLayout = <StackLayout>((<Vue>this.$refs.myLayout).nativeView)
const component = new classByClassName[this.type]
for (var i = 0; i< this.options.length; i++) {
const option = this.options[i];
component[option.key] = option.value
}
myLayout.addChild(component)
}
}

}
</script>

[Vue.js] Changing object from external file

when learning vue.js and before that there is some experience working with React.

As, I move on comprehending the basics of vue, I sort of compare things with JS

<template>
<div id=”app”>
<HelloWorld msg=”Below This we will inclue our To-do task list”/>
<p>{msg}</p>
<Todos :toDoItem=”todos”/>
</div>
</template>

import Todos from “./components/todo.vue”;
let todo =
{
name: “Rohit”,
title: “Full Stack Developer”,
completed: true
}

export default {
name: “app”,
components: {
HelloWorld,
Todos
},
data() {
return {
msg: “hello”,
todos: todo
};
}
};

We are passing the props here to child component and changing it using method

<template>
<div>
<div class=”main-class”>
<p>{toDoItem.title}</p>
<input type=”checkbox” v-on:change=”markComplete”>
</div>
</div>
</template>

<script>
export default {
name: “toDoItem”,
props: {
toDoItem: {
type: Object
}
},
method: {
markComplete() {
this.toDoItem.complete = !this.toDoItem.complete
}

};
</script>

This is where when unable to comprehend many things.

Question 1: Based on my understanding of this, shouldn’t it point to a global space and hence this should be undefined?

markComplete() {
this.toDoItem.complete = !this.toDoItem.complete
}

Question 2: In react we can’t change props passed to a child object probably? but here we are changing the props? Also, In general, if we declare a object in another file (app.js), can we change it to in another file (someApp.js)?

Solution :

All methods in a vue.js instance are bound to the instance so that this works properly.

You should not be changing props. Here, you are changing a member of a prop — toDoItem is a prop, and complete is a member of it — which is not controlled, but you still should not do it. You should instead emit an event that the parent handles.

the markComplete should be in the parent, since it owns the data being manipulated. It would look like:

markComplete() {
this.todos.complete = !this.todos.complete;
}

In the child, the method would be something like

toggleComplete() {
this.$emit(‘toggle’);
}

And the parent would use v-on to handle the toggle event:

<Todos :toDoItem=”todos” v-on:toggle=”markComplete”/>

This way all the code that manipulates data owned by a component happens within that component. Nobody calls anybody else’s methods or modifies their data.

I think you intend for todos to be an array of items, and probably want to v-for over them, having one child component for each item, but that’s another issue.

I cannot answer the last question about objects declared in different files, because I don’t understand it. It is not unusual to import objects and modify them, generally. As I mentioned, though, vue.js components should be the only ones to modify their own data.

[Vue.js] Utility method in Vue.js

when trying to create a utility method in Vue.js to validate a decimal number from any input field but I’m not sure how to set the value in Vue.js internally.

This is what I did in jQuery before:

$(‘body’).on(‘blur’, ‘.decimal’, function() {
var val = $(this).val();
if ($.isNumeric(val)) {
val = parseFloat(val).toFixed(2);
$(this).val(val);
} else {
$(this).val(‘’);
}
});

This is what there is in vue.js but the value is not stored internally and is overwritten.

function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

methods: {
validateDecimal: function (e) {
var val = e.target.value;

if (isNumeric(val)) {
e.target.value = parseFloat(val).toFixed(2);
} else {
e.target.value = ‘’;
}
}
}

HTML

<input class=”ui-input” :value=”some.value” placeholder=”0.00” @blur=”validateDecimal”>
<input class=”ui-input” :value=”some.othervalue” placeholder=”0.00” @blur=”validateDecimal”>
<input class=”ui-input” :value=”another.dynamic.input” placeholder=”0.00” @blur=”validateDecimal”>

Solution :

Apparently you can pass the data object reference to the handler method like so:
(Note you can’t just pass the data property, because I don’t believe it will be a reference.)

new Vue({
el: ‘#app’,
data: {
message: ‘Hello Vue.js!’,
inputs:{
‘v1’:{
value:’1.256’
},
‘v2’:{
value:’1.521’
}
},
someInput:{value:’1.7125’}
},
methods:{
validateDecimal: function (o,p,e) {
console.log(‘validateDecimal’,o);
var val = e.target.value;
console.log(val);
if (Number(parseFloat(val)) == val) {
val = parseFloat(val).toFixed(2);
this.$set(o, p, val);
} else {
this.$set(o, p, ‘’);
e.target.value = ‘’;
}
},
foo: function(){
console.log(this.inputs.v1.value)
console.log(this.inputs.v2.value)
}
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app”>
<div v-for=”i,key in this.inputs”>
<input class=”ui-input” :value=”i.value” placeholder=”0.00” @blur=”validateDecimal(i, ‘value’, $event)”>
</div>
<div>
<input class=”ui-input” :value=”this.someInput.value” placeholder=”0.00” @blur=”validateDecimal(someInput,’value’, $event)”>
</div>
<button @click=”foo”>Click</button>
</div>

Edit by OP: Adding an extra parameter for the name of the property and using $set to make the dynamic property reactive. This should make the method more general purpose for any dynamic input fields with any property name.

[Vue.js] Problem serving firebaseui.css in VueJS from node module

So basically I’ve got this problem for a long time now and thought I fixed it but that wasn’t the case.

I started the development of my site with this guide and it helped me create a PWA using the vue-cli.

While adding firebase authentication to it I also used this guide to add firebaseui to my project.

It told me to add this line to my index.html

<link type=”text/css” rel=”stylesheet” href=”node_modules/firebaseui/dist/firebaseui.css” />

sadly this didn’t worked out and I got this error message in my chrome console:

Refused to apply style from ‘http://localhost:8080/node\_modules/firebaseui/dist/firebaseui.css'
because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

This was 2 months ago and I tried a lot of things to fix this issue before finding a temporary solution:

When following the link to the CSS resource I got a “Cannot GET /node_modules/firebaseui/dist/firebaseui.css” in my browser and I thought that maybe my local server wasn’t serving this file.

So I went into the build/dev-server.js file and added this line:

app.use(express.static(‘node_modules’))

and changed the link in my index.html to:

<link type=”text/css” rel=”stylesheet” href=”/firebaseui/dist/firebaseui.css” />

Now my website correctly loads all firebaseui components when running “npm run dev” but now it still doesn’t do it when running “npm run build” as my server prints this:

“GET /firebaseui/dist/firebaseui.css” Error (404): “Not found”

I guess this makes sense, as when writing this down because I previously only changed the code in the dev-server.js and not in a build/production related file

Basically, when asking for a way to user the firebaseui.css without having to change stuff in the dev-server.js to have it work in production or for someone to tell what other files in the build directory there is to edit to make it work.

Thanks in advance and if you need to see more of my code pls ask for it and I will update this post!

Solution :

Holy shit, so I did more generic digging and found this discussion:

https://github.com/vuejs-templates/webpack/issues/604

fixed my issue by deleting both the import in the index.html and the now useless app.use line in dev-server.js

and now I simply added

import ‘firebaseui/dist/firebaseui.css’

in my main.js and the firebaseui components are rendering properly on both the dev and production build! :)

[Vue.js] Vue.js to display flow diagram

when new to Vue.js library. I would like to display flow of my task ( functional representation).
there is some sets of task running in linux box. to display the status of my task in UI thru API call.
Is there any element/ widget available in Vue.js to display ? More over there is dependency between 2 task.

Solution :

It is a broad question but there are a few cool projects that do that. Vue-diagrams is a not so popular one (that means that it may have some bugs) but it looks pretty neat, also amCharts is a really big library that allows you to choose more types of charts. It’s all up to you but those are the 2 that I find to be more interesting.

[Vue.js] How to add vanilla javascript function vue.js app?

for example there is vanilla JS function:

if (window.devicePixelRatio >= 2) {
document.querySelectorAll(‘img.retina’).forEach(function (e) {

let parts = e.src.split(‘.’);
let ext = parts.pop();

if (parts.join(‘.’).indexOf(‘@2x’) == -1) e.src = parts.join(‘.’) + ‘@2x.’ + ext;

});

}

Which just change the src of image if js detect retina display.
How can I use it in application using vue.js (where to put this function)?

If I put it into mounted, it doesnt work If I navigate throught SPA pages with router, it works only on first page load:

new Vue({
el: “#app”,
router,
render: h => h(App),
mounted() {
retinaFunction();
},
})

the retina function is not important, when mostly asking where and how can I use custom function in vanilla js in vue.js application.

Solution :

I would expect it to work in mounted, are you doing the modifications on this.$el…. or something else?

Note the caveat in the docs, https://vuejs.org/v2/api/#mounted

Note that mounted does not guarantee that all child components have
also been mounted. If you want to wait until the entire view has been
rendered, you can use vm.$nextTick inside of mounted:

Do you have child components? Perhaps you need to bundle it:

mounted(){
this.$nextTick(() => {
this.$el….;
}
}