link2192 link2193 link2194 link2195 link2196 link2197 link2198 link2199 link2200 link2201 link2202 link2203 link2204 link2205 link2206 link2207 link2208 link2209 link2210 link2211 link2212 link2213 link2214 link2215 link2216 link2217 link2218 link2219 link2220 link2221 link2222 link2223 link2224 link2225 link2226 link2227 link2228 link2229 link2230 link2231 link2232 link2233 link2234 link2235 link2236 link2237 link2238 link2239 link2240 link2241 link2242 link2243 link2244 link2245 link2246 link2247 link2248 link2249 link2250 link2251 link2252 link2253 link2254 link2255 link2256 link2257 link2258 link2259 link2260 link2261 link2262 link2263 link2264 link2265 link2266 link2267 link2268 link2269 link2270 link2271 link2272 link2273 link2274 link2275 link2276 link2277 link2278 link2279 link2280 link2281 link2282 link2283 link2284 link2285 link2286 link2287 link2288 link2289 link2290 link2291 link2292 link2293 link2294 link2295 link2296 link2297 link2298 link2299 link2300 link2301 link2302 link2303 link2304 link2305 link2306 link2307 link2308 link2309 link2310 link2311 link2312 link2313 link2314 link2315 link2316 link2317 link2318 link2319 link2320 link2321 link2322 link2323 link2324 link2325 link2326 link2327 link2328

[Vue.js] vuejs2 copy clipboard issue

when trying to use https://alligator.io/vuejs/vue-clipboard-copy/ for copy clip board feature in Vue.js, it is working fine for string but when there is an object, it is not copying properly. Below is the sample code.

<button v-clipboard:copy=”test”>Copy</button>

if test is a simple string then when getting that string properly copied to clipboard as abc in this case.

data() {
return {
test: ‘abc’
}
}

But when I give,

data() {
return {
test: {name: ‘abc’}
}
}

when getting [object object] into my clipboard instead {name: ‘abc’}

Solution :

Try this:

<button v-clipboard:copy=”JSON.stringify(test)”>Copy</button>

Solution 2:

Try this way

<button v-clipboard:copy=”stringConvertion”>Copy</button>

computed:{
stringConvertion: function () {
return JSON.stringify(test);
}
}

[Vue.js] Console log undefined after fetching api in Vue

When fetching from an API (3rd party, I authenticate and get the data in my Laravel Controller) I get ‘undefined’ in the console. to store the data in a vue.js component.

I tried a bunch of different things, including a get instead of fetch, but this also logged undefined. I did some research and read about arrow functions but when not using an arrow function.

data() {
return {
tickets: [],
};
},

created() {
this.fetchTickets();
},

methods: {
fetchTickets() {
fetch(‘/api’)
.then(res => {
this.tickets = res.json;
})
.then(res => {
console.log(res.json);
})
}
}

So, what is the collection made out of the get request I send to a 3rd party API in PHP which is returned to the route /api, stored in my vue.js component. Now it just logs undefined.

EDIT Backend request in PHP

$response = $client->get(‘v1/tickets/search.json’, [
‘query’ => [‘statuses[]‘ => ‘active’, ‘assignedTo[]‘ => 314955,
‘sortDir’ => ‘desc’, ‘sortBy’ => ‘updatedAt’]
]);

$json = (string)$response->getBody()->getContents();
$decoded = json_decode($json, true);
return collect($decoded);

Route:
Route::get(‘/api’, ‘ApiController@getTickets’,);

Solution :

fetch returns a promise containing the response res.
(This is just an HTTP response, not the actual JSON.)

To extract the JSON body content from the response, we use the json() method

You can read more about using fetch.

fetchTickets() {
fetch(‘/api’)
.then(res => res.json()) //returning a promise To extract the JSON body content from the response
.then(resJson => {
this.tickets = resJson
console.log(resJson);
})
}

Solution 2:

Return the data before going in second promise.

fetchTickets() {
fetch(‘/api’)
.then(res => {
this.tickets = res.json;
return res;
})
.then(res => {
console.log(res.json);
});

Solution 3:

add the return statement in the first promise

fetch(‘/api’)
.then(res => {
return res.json();
})
.then(tickets => {
// tickets is a local variable scoped only here
console.log(tickets);
})

[Vue.js] Nuxtjs property or method not defined on instance

I’m trying to get a counter to add 1 to a variable counter in a nuxtjs template. Not sure what is going on here:

<template>
<div class=”container”>
<div>
<h1>London Weather</h1>
<div id=”example-1”>
<button @click=”test()”>Add 1</button>
<p>The button above has been clicked { counter } times.</p>
</div>
</div>
</div>
</template>

<script>
import axios from ‘axios’

export default {
data: {
counter: 0
},
methods: {
test: function(counter) {
this.counter += 1
console.log(counter)
}
},
}
</script>

Solution :

Here’s one solution:

Reference counter as this.counter
data is a function which should return whatever data you need
test doesn’t need to take parameters as you are just changing the component’s state rather than modifying some parameter you’re passing in

<template>
<div class=”container”>
<div>
<h1>London Weather</h1>
<div id=”example-1”>
<button @click=”test”>Add 1</button>
<p>The button above has been clicked { counter } times.</p>
</div>
</div>
</div>
</template>

<script>
import axios from ‘axios’

export default {
data() {
return {
counter: 0
}
},
methods: {
test: function() {
this.counter += 1
console.log(this.counter)
}
}
}
</script>

See it live here

Solution 2:

Try the following:

<template>

<button @click=”test(1)”>Add 1</button>

</template>

<script>

methods: {
test(count) {
this.counter += count;
console.log(this.counter)
}
}

[Vue.js] TypeError Cannot read property 'replace' of undefined - VueJS

when trying to implement a simple authentication in vuejs by following this tutorial

But when I go to my browser when getting this error in my console “TypeError: Cannot read property ‘replace’ of undefined”. there is attached the screenshot of the same.

Here is my App.vue.js file

<template>
<div id=”app”>
<div id=”nav”>
<router-link v-if=”authenticated” to=”/login” v-on:click.native=”logout()” replace>Logout</router-link>
</div>
<router-view @authenticated=”setAuthenticated” />
</div>
</template>

<script>
export default {
name: ‘App’,
data() {
return {
authenticated: false,
mockAccount: {
username: “nraboy”,
password: “password”
}
}
},
mounted() {
if(!this.authenticated) {
this.$router.replace({ name: “login” });
}
},
methods: {
setAuthenticated(status) {
this.authenticated = status;
},
logout() {
this.authenticated = false;
}
}
}
</script>

<style>
body {
background-color: #F0F0F0;
}
h1 {
padding: 0;
margin-top: 0;
}

#app {
width: 1024px;
margin: auto;
}
</style>

Here is my Login component.

<template>
<div id=”login”>
<h1>Login</h1>
<input type=”text” name=”username” v-model=”input.username” placeholder=”Username” />
<input type=”password” name=”password” v-model=”input.password” placeholder=”Password” />
<button type=”button” v-on:click=”login()”>Login</button>
</div>
</template>

<script>
/* eslint-disable no-console */

export default {
name: ‘Login’,
data() {
return {
input: {
username: “”,
password: “”
}
}
},
methods: {
login() {
if(this.input.username !== “” && this.input.password !== “”) {
if(this.input.username === this.$parent.mockAccount.username && this.input.password === this.$parent.mockAccount.password) {
this.$emit(“authenticated”, true);
this.$router.replace({ name: “secure” });
} else {
console.log(“The username and / or password is incorrect”);
}
} else {
console.log(“A username and password must be present”);
}
}
}
}
</script>

<style scoped>

#login {
width: 500px;
border: 1px solid #CCCCCC;
background-color: #FFFFFF;
margin: auto;
margin-top: 200px;
padding: 20px;
}
</style>

And here is my router

import vue.js from ‘vue’
import Router from ‘vue-router’
import LoginComponent from “./components/Login”
import SecureComponent from “./components/Secure”

Vue.use(Router)

export default new Router({
routes: [
{
path: ‘/‘,
redirect: {
name: “login”
}
},
{
path: “/login”,
name: “login”,
component: LoginComponent
},
{
path: “/secure”,
name: “secure”,
component: SecureComponent
}
]
})

Since when new to vue.js when not able to figure out the exact cause of this error. Any help is deeply appreciated.

Solution :

It seems that the router is not working. In the main.js:

import router from ‘@/router’
new Vue({
router,
render: h => h(App)
}).$mount(‘#app’)

[Vue.js] data showing in console but not in vue template

when trying to fetch some data with vue.js from API that I created using Laravel Resource. The array in data is populating and showing in console perfectly. But when when trying to show the data in template under a v-for loop with v-bind, it is not showing anything. If I clear the cache in my browser, it is still not showing any data. But if I clear the cache in my browser while being on another page and then come back to the page where the vue.js template is using back button, the data is there till I refresh.

Here is the code in template:

<template>
<div>
<h2>Feeds</h2>
<div class=”card card-body” >
<ul>
<li v-for=”feed in feeds” v-bind:key=”feed.id”>
<h3>{feed.title}</h3>
<p>{feed.body}</p>
</li>
</ul>
</div>
</div>
</template>

And here is my script:

export default {
data(){
return {
feeds: []
}
},
created(){
this.fetchFeeds();
},
methods:{
fetchFeeds(page_url){
let vm = this;
page_url= page_url ||’feeds/api’
fetch(page_url)
.then(res => res.json())
.then(res =>{
vm.feeds = res.data;
console.log(vm.feeds);
})
.catch(err => console.log(err));
}
}
}

Solution :

It can be vue.js reactivity issue.
Try using Object.assign as below

fetchFeeds(page_url){
let vm = this;
page_url= page_url ||’feeds/api’
fetch(page_url)
.then(res => res.json())
.then(res =>{

vm.feeds = Object.assign({}, res.data);
console.log(vm.feeds);
})
.catch(err => console.log(err));
}

}

[Vue.js] Export multiple parts module in single file component in Vue in TS

My single page component file:

<template>
<div></div>
</template>

<style lang=”scss” scoped>
</style>

<script lang=”ts”>
export const component = Vue.extend({…});//This is my component.
export let foo = ‘bar’; //Other vars to export.
</script>

Where to import the component:

import * as myComp from ‘./path_to_file_above’;//Import the file above
Vue.extend({
components:{
myComp:myComp.component;//Register the component exported.
},
mounted(){
console.log(myComp.foo);//Use other vars exported.
}
})

Got error:

Uncaught TypeError: Cannot set property ‘render’ of undefined
at normalizeComponent (componentNormalizer.js?2877:24)
at eval (PageEditor.vue?e50e:9)
at Module../src/components/PageEditor.vue.js (app.js:7568)
at __webpack_require__ (app.js:724)
at fn (app.js:101)
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/Designer.vue?vue&type=script&lang=ts&:36)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/Designer.vue?vue&type=script&lang=ts& (app.js:2736)

Is the single page component support export multiple parts module? If not how do I export other informations about the component?

Solution :

Just export component as default and export other vars in other names, and register the component with myComp.default:

export default Vue.extend({
//my component
})
export let foo = ‘bar’//other vars

import * as myComp from ‘./path_to_file_above’;
Vue.extend({
components:{myComp:myComp.default},
mounted(){console.log(myComp.foo)}
})

[Vue.js] Can't receive data from axios on API

there is an axios post request on my vue.js frontend which sends some data to an API endpoint (express). The problem is that I can’t see any data on the controller that receive the post request.

//app.js

var express = require(‘express’)
var cors = require(‘cors’)
var app = express()
var port = process.env.port || 1337

app.use(cors({origin: true}));
var imagenmatriculaController = require(‘./controllers/imagenmatriculaController.js’)()

app.use(“/api/imagenmatricula”, imagenmatriculaController)

app.listen(port, function () {})

//imagenmatriculaController.js

var express = require(‘express’)
var router = express.Router()
var routes = function (){
router.route(‘/‘)
.post(function(req,res){

console.log(req.data)
res.json(‘ok’)
})
return router
}

module.exports = routes

I do receive the request log on the server and the ‘ok’ back to the client but I get an undefined on the console.log(req.data);

//vue.js post

var headers = {
‘Content-Type’: ‘application/json;charset=UTF-8’,
‘Access-Control-Allow-Origin’: ‘*‘
};

axios.post(‘http://localhost:1337/api/imagenmatricula', {
headers: headers,
data: ‘test’
})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
console.log(‘ERROR::’, error.response.data);
});

Solution :

In order to receive json data on backend you need to setup parser. You could use body-parser. Then the code should look like this

var express = require(‘express’)
var cors = require(‘cors’)
var app = express()
var port = process.env.port || 1337
var bodyParser = require(‘body-parser’)

app.use(cors({origin: true}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
var imagenmatriculaController = require(‘./controllers/imagenmatriculaController.js’)()

app.use(“/api/imagenmatricula”, imagenmatriculaController)

app.listen(port, function () {})

//imagenmatriculaController.js

var express = require(‘express’)
var router = express.Router()
var routes = function (){
router.route(‘/‘)
.post(function(req,res){

console.log(req.body)
res.json(‘ok’)
})
return router
}

module.exports = routes

Client should look like this:

var headers = {
‘Content-Type’: ‘application/json;charset=UTF-8’,
‘Access-Control-Allow-Origin’: ‘*‘
};

axios.post(‘http://localhost:1337/api/imagenmatricula', {
headers: headers,
data: { test: ‘test’ }
})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
console.log(‘ERROR::’, error.response.body);
});

If the routing on server is correctly setup, this should work.

Solution 2:

You need to have body-parser in order to use json data in node and express. So in order to make the code work. First install body-parser through ‘npm install body-parser’ command then use it as middleware in the code as shown below:

var express = require(‘express’)
var cors = require(‘cors’)
var app = express()
var port = process.env.port || 1337
var bodyParser = require(‘body-parser’)

app.use(cors({origin: true}));

//It will parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

//It will parse application/json
app.use(bodyParser.json())

var imagenmatriculaController = require(‘./controllers/imagenmatriculaController.js’)()

app.use(“/api/imagenmatricula”, imagenmatriculaController)

app.listen(port, function () {})

In imagenmatriculaController.js write,

var express = require(‘express’)
var router = express.Router()
var routes = function (){
router.route(‘/‘)
.post(function(req,res){

console.log(req.body)
res.json(‘ok’)
})
return router
}

module.exports = routes

the front end client should contain following code:

var headers = {
‘Content-Type’: ‘application/json;charset=UTF-8’,
‘Access-Control-Allow-Origin’: ‘*‘
};

axios.post(‘http://localhost:1337/api/imagenmatricula', {
headers: headers,
data: { test: ‘test’ }
})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
console.log(‘ERROR::’, error.response.body);
});

Note:: If you are using higher version of express i.e v4.16.0 then instead of using bodyParser.json() and bodyParser.urlencoded() you can use express.json() and express.urlencoded() because it is built-in middleware of express from version v4.16.0. So choose wisely,

app.use(express.json())
app.use(express.urlencoded())

[Vue.js] Svg.js How do i use svg.js plugins in vue.js?

when using svg.js in my Laravel project running vue.js.

This is how i use svg.js

Step 1: Install svg.js as a plugin in my vue.js app.

import svgJs from “svg.js/dist/svg”

export default {
install(Vue) {
Vue.prototype.$svg = svgJs
}
}

Step 2: Import and use the plugin.

import svgJs from “./plugins/vueSvgPlugin”

Vue.use(svgJs);

Step 2: Then i can do this.

console.log(this.$svg);

console.log(this.$svg.get(“samplesvg”));

However when not sure how to add the svg.js plugins. to use below three plugins, in case someone wants to know.

svg.select.js
svg.resize.js
svg.draggable.js

Solution :

there is my solution for working with non npm/module library.

First I will use jsdelivr to serve file from directly from Github. For example https://cdn.jsdelivr.net/npm/svg.js@2.7.1/dist/svg.min.js.

Then I use script.js to load them.

script.order([
https://cdn.jsdelivr.net/npm/svg.js@2.7.1/dist/svg.min.js",
https://cdn.jsdelivr.net/npm/svg.select.js@3.0.1/dist/svg.select.min.js"
], () => {
// window.SVG is available
});

Live Example

[Vue.js] how to use this in vue components default prop function

export default {
props: {
goToSomePage: {
type: Function,
default: () => { this.$router.push({ name: ‘some-page’ }) }
}
}
}

do something like this but “this” is undefined.

Is there any way to solve this problem?

to give a default action and use “this” inside that callback func.

Solution :

The reason the attempt does not work is because:

You used arrow function where this is lexical.
vue.js does not automatically bind functions passed to props property with any vue.js instance. So this is automatically bind to the window (global) object.

You can try something like this:

new Vue({
el: ‘#app’,
props: {
goToSomePage: {
type: Function
}
},
computed: {
computedGoToSomePage(){
// If `goToSomePage` prop is provided, return that function
if (typeof this.goToSomePage === ‘function’)
return this.goToSomePage.bind(this);

// Else, return the intended $router function here
return (() => {
/* UNCOMMENT THIS IN the CODE */
// this.$router.push({ name: ‘some-page’ })

// This is to prove that `this` is referencing the vue.js instance
console.log(this);
})
}
}
});
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id=”app”>
<button @click=”computedGoToSomePage”>Go To Some Page</button>
</div>

The method above make use of computed property to pass the function. Using that, vue.js magically bind this to its parent vue.js instance.

Solution 2:

For arrow function this is not defined. You can use it only in function:

goToSomePage: {
type: Function,
default: function() { this.$router.push({ name: ‘some-page’ }) }
}

[Vue.js] How pass a Bearer token in Axios

I look for an answer this morning and try lot of things but my axios API Call always failed with a 401 error.

Furthemore if I try a curl from the console or postman the request works and I don’t understand why on my front with vue.js and axios it’s failed.

I tried to pass the bearer globally, then for a unique route

First of all there is the configuration of my module for Axios

export default() => {
return axios.create({
baseURL: process.env.VUE_APP_API,
headers: {
‘Content-Type’: ‘application/json’,
Authorization: ‘Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIn0.wxYD9dllTqT1gAIBmwo35Z4Q4qmlDZwXqz9FdYqXZnU’
}
})
}

Then there is my request

Api().get(`user-profiles/${id}`).then(function (response) {
return(response)
})

The request is this one:

Request URL: https://***
Request Method: OPTIONS
Status Code: 401
Remote Address: ****
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Location
Provisional headers are shown
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:8080
Referer: http://localhost:8080/login
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Mobile Safari/537.36

Do you need other data ?
The request works if I don’t use a Bearer token…

I need to pass a Bearer token because for production release I can’t take off the bearer.

Thank you in advance for the help.

Solution :

h’ttps://stackoverflow.com/questions/45578844/how-to-set-header-and-options-in-axios

Like mentioned here in the best answer, you should go for

export default() => {
return axios.create({
baseURL: process.env.VUE_APP_API,
headers: {
‘get’: {
‘Content-Type’: ‘application/json’,
Authorization: ‘Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIn0.wxYD9dllTqT1gAIBmwo35Z4Q4qmlDZwXqz9FdYqXZnU’
}
}
})
}

Solution 2:

After some search I found the solution…
You need to authorize the backend with cors policies…
On my own backend in node js that works… I wait the fix for the java api backend ;)