link0 link1 link2 link3 link4 link5 link6 link7 link8 link9 link10 link11 link12 link13 link14 link15 link16 link17 link18 link19 link20 link21 link22 link23 link24 link25 link26 link27 link28 link29 link30 link31 link32 link33 link34 link35 link36 link37 link38 link39 link40 link41 link42 link43 link44 link45 link46 link47 link48 link49 link50 link51 link52 link53 link54 link55 link56 link57 link58 link59 link60 link61 link62 link63 link64 link65 link66 link67 link68 link69 link70 link71 link72 link73 link74 link75 link76 link77 link78 link79 link80 link81 link82 link83 link84 link85 link86 link87 link88 link89 link90 link91 link92 link93 link94 link95 link96 link97 link98 link99 link100 link101 link102 link103 link104 link105 link106 link107 link108 link109 link110 link111 link112 link113 link114 link115 link116 link117 link118 link119 link120 link121 link122 link123 link124 link125 link126 link127 link128 link129 link130 link131 link132 link133 link134 link135 link136

[Vue.js] How to use NPM package in Vue if it requires Nodejs filesystem (fs)

Every time I attempt to use an NPM package in vue.js that requires fs it doesn’t work and it errors out. Normally along the lines of fs could not be resolved or fs.readFileSync is not a function.

there is seen some other pages that say fs doesn’t work in browsers because of permission etc…

Just to add, when not explicitly trying to use the fs module. when just trying to use the npm package which happens to use fs.

What should I do to make it work? Ive tested these packages on the npm runkit, and everything is fine. And that runs in a browser, so I’m a little confused there also.

Solution :

The problem here is that vue.js will be rendered client side.
fs is just for node applications, because it is server side (you should not be able to read data from a client file system).
You you have two options:

Not using the module
Or, if you do not need the fs part and the module is under a open source
license (which
the module you mentioned in comments is): copying the module and removing the
fs part

[Vue.js] How to bind an event to a treeview node in Vuetify?

when currently making a treeview using Vuetify. What when trying to do is that to bind an event whenever I click on a node. For example when I click on a certain node a dialog box will pop out to show the node’s details. to know how to fire off an event on click.

Solution :

Vuetify’s Treeview component provides a scoped slot label that you can use to change the content displayed for each node. For example, to open a dialog box, you could do something like this:

<v-treeview
v-model=”tree”
:items=”items”
activatable
item-key=”name”>
<template slot=”label” slot-scope=”{ item }”>
<a @click=”openDialog(item)”>{ item.name }</a>
</template>
</v-treeview>

You can then use a dialog component and open it/change its contents using a openDialog method

[Vue.js] How can I use a Global Mixin method from a Vue instance

Let’s suppose that there is the following situation, using a Global Mixin to create a global helper method with Vue:

import vue.js from “vue”;

Vue.mixin({
methods: {
replaceString: function (word) {
return word.toLowerCase().replace(/\W/g, ‘’);
}
}
});

let vm = new Vue({
methods: {
doSomething: function() {
console.log(this.replaceString(‘Hello World’); //helloword
}
}
});

I know that I can invoke the method inside the other methods, inside of the component and their childs. But how can I invoke the mixin method “replaceString” from the vue.js instance “vm”?
I tried to use “vm.replaceString”, but keeps returning “undefined”.

Solution :

I think this chunk o code is what you are looking for:

var mixin = {
methods: {
foo: function () {
console.log(‘foo’)
},
conflicting: function () {
console.log(‘from mixin’)
}
}
}

var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log(‘bar’)
},
conflicting: function () {
console.log(‘from self’)
}
}
})

vm.foo() // => “foo”
vm.bar() // => “bar”
vm.conflicting() // => “from self”

From the docs

[Vue.js] Using ref in vue to modify the style of an element sends an error in the toggle routing

I use vue.js to bind an img tag through ref in a route and have it rotate periodically. But it show Uncaught TypeError: Cannot read property ‘style’ of undefined. I know it’s because this.$refs.image becomes undefined after switching the routing, but I don’t know how to solve this problem so that it doesn’t give an error. Can you help me?

<img :src=”this.picUrl” ref=”image”>

rotateMusicLogo() {
this.timer = setInterval(() => {
this.deg += 0.15;
if(this.deg >= 360) this.deg = 0;
this.$refs.image.style.transform = `rotate(${this.deg}deg)`;
}, 10)
}

Solution :

you should destroy the timer on the beforeDestroy hook:

<script>
export default {
data () {
return {
timer: null
}
},
methods: {
rotateMusicLogo () {
this.timer = setInterval(() => {
this.deg += 0.15;
if(this.deg >= 360) this.deg = 0;
this.$refs.image.style.transform = `rotate(${this.deg}deg)`;
}, 10)
}
},
mounted () {
this.rotateMusicLogo()
},
beforeDestroy () {
clearInterval(this.timer)
}
}
</script>

Solution 2:

You should just clear the interval you created when the route change. So, in the component;

watch:{
$route (to, from){
clearInterval(this.timer)
}
}

[Vue.js] put vue variable with mounted on section('title')

there is problem with showing vue.js variable on blade template

my layouts/master.blade.php

<html>
<head>
<title>@yield(‘title’) | My company</title>
…..

news.blade.php

@extends(‘layouts.master’)

<div id=”pagetitle”>
@section(‘title’, @{pagetitle} )
</div>

@section(‘content’)
….
@endsection

resources/js/news.js

new Vue({

el: ‘#pagetitle’,

data: {
pagetitle:’’,
},

mounted() {
this.fetchArticlesPage();
},

methods: {
fetchArticlesPage(page_url) {
page_url = ‘/api/articles/news’;
fetch(page_url)
.then(res => res.json())
.then(res => this.pagetitle = res.page_title)
.catch(err => console.log(err));
},

}
});

and this response data from controller with jsonResource

{
“links”: {
“first”: “http://localhost:8000/api/articles/news?page=1",
“last”: “http://localhost:8000/api/articles/news?page=1",
“prev”: null,
“next”: null
},
“meta”: {
“current_page”: 1,
“from”: 1,
“last_page”: 1,
“path”: “http://localhost:8000/api/articles/news",
“per_page”: 3,
“to”: 3,
“total”: 3
},
“page_title”: “News”
}

i got syntax error unexpected {

if i put on @section(‘content’) like this

@section(‘content’)
<div id=”pagetitle”>
@{pagetitle}
</div>
@stop

it’ fine and will show the data which is “News”,
please help, am new in vue.js and laravel programing

Solution :

The Blade template directives are processed in the server and a response sent to the client.

After this, vue.js template directives are processed in the browser.

On that account, the later example with the escaped vue.js mustache works as expected as the block below is sent to the browser as a part of the overall response content.

<div id=”pagetitle”>
{pagetitle}
</div>

The vue.js program running in the browser then runs, and interpolates variables in this template.

For the former example,

@section(‘title’, @{pagetitle})

will result in an error in the server when it tries to compile the section as the second parameter is not given as a string.

This error can be corrected by quoting the escaped vue.js mustache.

@section(‘title’, ‘@{pagetitle}’)

EDIT: {pagetitle} is not compiled is in document head

The vue.js instance that is created is mounted on an element contained in the body. For this reason, compilation happens only on the document tree of the element that the vue.js instance is mounted on.

I suggest to create a separate vue.js instance to manage the head of the document. e.g.

const helmet = new Vue({
el: ‘head’,
data: {
pagetitle:’’,
},

mounted() {
this.fetchArticlesPage();
},

methods: {
fetchArticlesPage(page_url) {
page_url = ‘/api/articles/news’;
fetch(page_url)
.then(res => res.json())
.then(res => this.pagetitle = res.page_title)
.catch(err => console.log(err));
},

}
})

[Vue.js] Parameter Url Vue Js

when trying to build a filter component with vue.js , example there is 2 input form 1. Min Price and 2 Max Price and the query text that the user enters in an input field to be reactive with the query parameter in the URL
example i input min price : 1000

localhost/minprice=1000

when i input maxprice : 2000 the url be like :

localhost/minprice=1000&maxprice=2000

how to add multiple query parameter in the address without change the last parameter url there is ?

thanks

Solution :

You can add a submit button, and then create a URL with query parameters using bound data, finally set the location object.

// in click handler
const url = `localhost://thePage?minprice=${this.minPrice}&maxprice=${this.maxprice}`

IMO it might be better to use the hash part of the URL, instead of query param, so the page does not need to reload.

const url = `localhost://thePage#minprice=${this.minPrice}&maxprice=${this.maxprice}`

You would filter in the component (without refreshing), and also set the hash. Then if the user refreshed or bookmarked, the filter would be persisted.
window.location.hash = …

Either way, you would read the URL properties when loading the component and set the bound properties to them.

[Vue.js] How to fire an event when v-model changes ? (vue js)

I’m trying to fire the foo() function with the @click but as you can see, need press the radio button two times to fire the event correctly . Only catch the value the second time that you press…

to fire the event without @click only fire the event when v-model (srStatus) changes.

here is my Fiddle:

http://fiddle.jshell.net/wanxe/vsa46bw8/

Solution :

This happens because the click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input
type=”radio”
name=”optionsRadios”
id=”optionsRadios2”
value=””
v-model=”srStatus”
v-on:change=”foo”> //here

Also, make sure you really want to call foo() on ready… seems like maybe you don’t actually want to do that.

ready:function(){
foo();
},

Solution 2:

You can actually simplify this by removing the v-on directives:

<input type=”radio” name=”optionsRadios” id=”optionsRadios1” value=”1” v-model=”srStatus”>

And use the watch method to listen for the change:

new vue.js ({
el: “#app”,
data: {
cases: [
{ name: ‘case A’, status: ‘1’ },
{ name: ‘case B’, status: ‘0’ },
{ name: ‘case C’, status: ‘1’ }
],
activeCases: [],
srStatus: ‘’
},
watch: {
srStatus: function(val, oldVal) {
for (var i = 0; i < this.cases.length; i++) {
if (this.cases[i].status == val) {
this.activeCases.push(this.cases[i]);
alert(“Fired! “ + val);
}
}
}
}
});

Solution 3:

Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)

<input @change=”foo” v-model… >

If you wanna detect single character changes (during user typing) use

<input @keyDown=”foo” v-model… >

You can also use @keyUp and @input events. If you wanna to pass additional parameters use in template e.g. @keyDown=”foo($event, param1, param2)”. Comparision below (editable version here)

new Vue({
el: “#app”,
data: {
keyDown: { key:null, val: null, model: null, modelCopy: null },
keyUp: { key:null, val: null, model: null, modelCopy: null },
change: { val: null, model: null, modelCopy: null },
input: { val: null, model: null, modelCopy: null },

},
methods: {

keyDownFun: function(event){ // type of event: KeyboardEvent
console.log(event);
this.keyDown.key = event.key; // or event.keyCode
this.keyDown.val = event.target.value; // html current input value
this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling
},

keyUpFun: function(event){ // type of event: KeyboardEvent
console.log(event);
this.keyUp.key = event.key; // or event.keyCode
this.keyUp.val = event.target.value; // html current input value
this.keyUp.modelCopy = this.keyUp.model; // copy of model value at the moment on event handling
},

changeFun: function(event) { // type of event: Event
console.log(event);
this.change.val = event.target.value; // html current input value
this.change.modelCopy = this.change.model; // copy of model value at the moment on event handling
},

inputFun: function(event) { // type of event: Event
console.log(event);
this.input.val = event.target.value; // html current input value
this.input.modelCopy = this.input.model; // copy of model value at the moment on event handling
}
}
})
div {
margin-top: 20px;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Type in fields below (to see events details open browser console)

<div id=”app”>
<div><input type=”text” @keyDown=”keyDownFun” v-model=”keyDown.model”><br> @keyDown (note: model is different than value and modelCopy)<br> key:{keyDown.key}<br> value: { keyDown.val }<br> modelCopy: {keyDown.modelCopy}<br> model: {keyDown.model}</div>

<div><input type=”text” @keyUp=”keyUpFun” v-model=”keyUp.model”><br> @keyUp (note: model change value before event occure) <br> key:{keyUp.key}<br> value: { keyUp.val }<br> modelCopy: {keyUp.modelCopy}<br> model: {keyUp.model}</div>

<div><input type=”text” @change=”changeFun” v-model=”change.model”><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: { change.val }<br> modelCopy: {change.modelCopy}<br> model: {change.model}</div>

<div><input type=”text” @input=”inputFun” v-model=”input.model”><br> @input<br> value: { input.val }<br> modelCopy: {input.modelCopy}<br> model: {input.model}</div>

</div>

Solution 4:

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click=”doSomething”>

So in this example it would be

v-on:change=”foo”

See: http://v1.vuejs.org/guide/syntax.html#Arguments

Solution 5:

You should use @input:

<input @input=”handleInput” />

@input fires when user changes input value.

@change fires when user changed value and unfocus input (for example clicked somewhere outside)

You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/

[Vue.js] How to properly record stream from canvas?

THE SITUATION:

I need to do the following:

Get the video from a <video> and play inside a <canvas>
Record the stream from the canvas as a Blob

That’s it. First part is okay.
For the second part I managed to record a Blob, the problem is that the Blob is empty.

THE VIEW:

<video id=”video” controls=”true” src=”http://upload.wikimedia.org/wikipedia/commons/7/79/Big\_Buck\_Bunny\_small.ogv"></video>
<canvas id=”myCanvas” width=”532” height=”300”></canvas>

THE CODE:

// Init
console.log(MediaRecorder.isTypeSupported(‘video/webm’)) // true
const canvas = document.querySelector(“canvas”)
const ctx = canvas.getContext(“2d”)
const video = document.querySelector(“video”)

// Start the video in the player
video.play()

// On play event - draw the video in the canvas
video.addEventListener(‘play’, () => {
function step() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
requestAnimationFrame(step)
}
requestAnimationFrame(step);

// Init stream and recorder
const stream = canvas.captureStream()
const recorder = new MediaRecorder(stream, {
mimeType: ‘video/webm’,
});

// Get the blob data when is available
let allChunks = [];
recorder.ondataavailable = function(e) {
console.log({e}) // img1
allChunks.push(e.data);
}

// Start to record
recorder.start()

// Stop the recorder after 5s and check the result
setTimeout(() => {
recorder.stop()
const fullBlob = new Blob(allChunks, { ‘type’ : ‘video/webm’ });
const downloadUrl = window.URL.createObjectURL(fullBlob)
console.log({fullBlob}) // img2
}, 5000);
})

THE RESULT:

This the console.log of the ondataavailable event:

This is the console.log of the Blob:

THE FIDDLE:

Here is the JsFiddle. You can check the results in the console:

https://jsfiddle.net/1b7v2pen/

BROWSERS BEHAVIOR:

This behavior (Blob data size: 0) it happens on Chrome and Opera.
On firefox it behaves slightly different.
It records a very small video Blob (725 bytes). The video length is 5 seconds as it should be, but it’s just a black screen.

THE QUESTION:

What is the proper way to the record a stream from a canvas?
Is there something wrong in the code?
Do you know why the Blob came out empty?

Thanks!

Solution :

MediaRecorder.stop() is kind of an asynchronous method.

In the stop algorithm, there is a call to requestData, which itself will queue a task to fire an event dataavailable with the currently available data since the last such event.

This means that synchronously after you called MediaRecorder#stop() the last data grabbed will not be part of the allChunks Array yet. They will become not so long after (normally in the same event loop).

So, when you are about to save recordings made from a MediaRecorder, be sure to always build the final Blob from the MediaRecorder’s onstop event, which will signal that the MediaRecorder is actually ended, did fire its last dataavailable event, and that everything is all good.

And one thing I missed at first, is that you are requesting a cross-domain video. Doing so, without the correct cross-origin request, will make the canvas (and MediaElement) tainted, so the MediaStream will be muted.

Since the video you are trying to request is from wikimedia, you can simply request it as a cross-origin resource, but for other resources, you’ll have to be sure the server is configured to allow these requests.

const canvas = document.querySelector(“canvas”)
const ctx = canvas.getContext(“2d”)
const video = document.querySelector(“video”)

// Start the video in the player
video.play()

// On play event - draw the video in the canvas
video.addEventListener(‘play’, () => {
function step() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
requestAnimationFrame(step)
}
requestAnimationFrame(step);

// Init stream and recorder
const stream = canvas.captureStream()
const recorder = new MediaRecorder(stream, {
mimeType: ‘video/webm’,
});

// Get the blob data when is available
let allChunks = [];
recorder.ondataavailable = function(e) {
allChunks.push(e.data);
}
recorder.onstop = (e) => {
const fullBlob = new Blob(allChunks, { ‘type’ : ‘video/webm’ });
const downloadUrl = window.URL.createObjectURL(fullBlob)
console.log({fullBlob})
console.log({downloadUrl})
}

// Start to record
recorder.start()

// Stop the recorder after 5s and check the result
setTimeout(() => {
recorder.stop()
}, 5000);
})
<!–add the ‘crossorigin’ attribute to the video –>
<video id=”video” controls=”true” src=”https://upload.wikimedia.org/wikipedia/commons/7/79/Big\_Buck\_Bunny\_small.ogv" crossorigin=”anonymous”></video>
<canvas id=”myCanvas” width=”532” height=”300”></canvas>

Also, I can’t refrain to note that if you don’t do any special drawings from the canvas, you might want to save the video source directly, or at least, record the <video>’s captureStream MediaStream directly.

[Vue.js] How do I pass data from PHP Laravel to Vue.js and re-render a Vue.js component when the data changes?

I’m still a bit new to Vue.js, so I may be fundamentally misunderstanding something about the reactivity of it, but basically, to pass some data from PHP Laravel to a Vue.js component and have the Vue.js component automatically update when that data changes.

I’ve seen several similar posts on SO suggest that I use props to pass the data from a Laravel Blade template to a Vue.js component. Here’s an example:
How to pass a PHP variable to vue.js component instance in Laravel blade?

there is this working perfectly fine, but now I’m stuck with how to get the component to update when the data dynamically changes after page-load.

Specifically, there is a report table on a particular web page, and when the user clicks certain buttons, etc., I use Ajax to call a Laravel controller action that re-runs a query in my Laravel model to get the new data for the report.

there is the data in a PHP array / JSON, and that data is being properly returned to the client-side and there is access to it in the JS, but now, what do I need to do to force the report component in Vue.js to essentially re-render based on the data I just received? Is there a way to “update props” so that Vue.js detects the change and automatically re-renders the whole report component for me?

This is where I’m stuck, and after quite a bit of research, I can’t find how to do this. Thank you.

Solution :

Are you using Ajax outside of the vue.js component? or within it as a method?

there is an example of how I dynamically update the vue.js data from within the component itself. I’m not sure how to have external JS update the vue.js component directly but I feel this is a good option to look at. I’m using axios instead of Ajax but the principle is the same (Axios is included by default in most Laravel installs past 5.5).

<template>
<div>
<div id=”reports”>
<!– Display data –>
{ reports }
</div>
<button @click=”refreshReports”>Refresh</button>
</div>
</template>

<script>
export default {
data() {
return {
endpoint: ‘/api/MY_ROUTE/‘
};
},

props: {
reports: Object
},

methods: {
// Make Axios call to API endpoint
refreshReports() {
// GET version
axios.get(this.endpoint)
.then(({data}) => {
this.reports = data.data;
});

// POST version
axios.post(this.endpoint, {
KEY: ‘VALUE’,
}).then(({data}) => {
this.reports = data.data;
});

/*
`data.data` assumes the returned response is a JSON Resource

if it’s not returning the correct data, put a `console.log(data)` and see how it’s getting returned!
*/
}
}
};
</script>

Where in the routes/api.php file you have a route like this:

// GET version
Route::get(‘MY_ROUTE’, ‘ReportController@getReports’);

// POST version
Route::post(‘MY_ROUTE’, ‘ReportController@getReports’);

And the Controller would have some method like this:

// app/Http/Controllers/ReportController
public function getReports(Request $request) {
return Reports::all();
}

Does that make sense?

Update:

I’m not sure how to have external JS update the vue.js component directly

I know you can import external JS scripts and use their functions in methods but I’ve never done it that way before.

Something like:

<script>
import { myFunction } from ‘../external.js’

export default {
methods: {
refreshReports() {
// there is no idea if this is the correct way to do it, just a guess!
this.reports = myFunction();
}
}
};
</script>

[Vue.js] Axios post to nodejs server but nodejs cannot get data

i post from vuejs cli with axios to nodejs express server:

axios.post(‘http://localhost:8081/users', bar)
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error)
})

and server:

app.post(‘/users’, (req, res) => {
console.log(req.body.bar)
res.json(req.body.bar)
})

in http://localhost:8081/users i got Cannot GET /users and console log windows: undefined

please help me!

Solution :

axios.post(‘http://localhost:8081/users', {foo: “Bar”})
.then((response)=> {
console.log(response.data) // must be show “Bar”
})
.catch((error)=> {
console.log(error)
})

app.post(‘/users’, (req, res) => {
console.log(req.body.foo) // must be show “Bar”
res.send(req.body.foo)
})