link3151 link3152 link3153 link3154 link3155 link3156 link3157 link3158 link3159 link3160 link3161 link3162 link3163 link3164 link3165 link3166 link3167 link3168 link3169 link3170 link3171 link3172 link3173 link3174 link3175 link3176 link3177 link3178 link3179 link3180 link3181 link3182 link3183 link3184 link3185 link3186 link3187 link3188 link3189 link3190 link3191 link3192 link3193 link3194 link3195 link3196 link3197 link3198 link3199 link3200 link3201 link3202 link3203 link3204 link3205 link3206 link3207 link3208 link3209 link3210 link3211 link3212 link3213 link3214 link3215 link3216 link3217 link3218 link3219 link3220 link3221 link3222 link3223 link3224 link3225 link3226 link3227 link3228 link3229 link3230 link3231 link3232 link3233 link3234 link3235 link3236 link3237 link3238 link3239 link3240 link3241 link3242 link3243 link3244 link3245 link3246 link3247 link3248 link3249 link3250 link3251 link3252 link3253 link3254 link3255 link3256 link3257 link3258 link3259 link3260 link3261 link3262 link3263 link3264 link3265 link3266 link3267 link3268 link3269 link3270 link3271 link3272 link3273 link3274 link3275 link3276 link3277 link3278 link3279 link3280 link3281 link3282 link3283 link3284

[Vue.js] Do not go to a new page Vue-router

I’m new in vue.js js. And my task is to take data from api, make pagination and when clicking on any post so that a new page opens with more detailed information about the post. I did the pagination, but I can’t make the transition. In clicking on the post, the link changes but the transition is not performed.

Project on GitHub

My main code:

<template>
<div id=”app”>
<ul>
<li v-for=”(post, index) of paginatedData” class=”post”>
<router-link :to=”{ name: ‘detail’, params: {id: index} }”>
<img src=”src/assets/nature.jpg”>
<p class=”boldText”> { post.title }</p>
</router-link>
<p> { post.body }</p>
</li>
</ul>

</div>
</template>

<script>
import axios from ‘axios’;
export default {
el: “#app”,
data () {
return {
current: null,
page: 0,
posts: [],
}
},
created(){
this.getData()
},
methods: {
setCurrent: function(id) {
this.current = id;
},
getData() {
axios.get(`https://jsonplaceholder.typicode.com/posts\`).then(response => {
this.posts = response.data
})
},
}
}
</script>

My detail post page:

<template>
<div class=”post” v-if=”detail”>
<img src=”src/assets/nature.jpg”>
<h2>{ post.title }</h2>
<p>{ post.body }</p>
</div>
</template>

<script>
module.exports = {
data: function() {
return {
posts: [],
}
},
created: function() {
var postId = this.$route.params.id
this.post = this.posts[postId]
}
}
</script>

My main.js:

import vue.js from ‘vue’
import App from ‘./App.vue’
import VueRouter from ‘vue-router’

var Detail = require(‘./Detail.vue’)

Vue.use(VueRouter)

var router = new VueRouter({
routes: [
{path: ‘detail/:id’, name: ‘detail’, component: Detail }
]
})

new Vue({
el: ‘#app’,
render: h => h(App),
router: router,
})

Solution :

You need a router-view tag. This basically renders the routed component inside the tags.

https://router.vuejs.org/guide/#html

[Vue.js] Using v-if to show an html element based on the value of a variable

I’m trying to show a <div> element (that contains a few nested <div>s) based on the value of a variable. I’m using v-if (though if there’s a better way to go about it, please let me know).

I tried wrapping the whole <div> in a <template v-if> (per https://vuejs.org/v2/guide/conditional.html's suggestion), but that didn’t work, and I used devtools to verify that my variable is being accurately set.

<div v-if=”var == ‘option1’ || ‘option2’” class=”…
<div>…
</div>
</div>

Even when var doesn’t equal option 1 or option 2, the element is still visible.

EDIT: I added v-if=”var==’option1’” to an <img> and it is acting as intended - is there something about or(||) that I’m using incorrectly?

Solution :

In JavaScript, || produces the value of first operand if it is a truthy value or the value of the second operand if first is not truthy.
Therefore, ‘option1’ || ‘option2’ will always produce ‘option1’ (read below).

A few considerations:

Never use reserved words (i.e: var) to name the functions or variables.
the expression ‘option1’ || ‘option2’ will always return ‘option1’, as ‘option1’ is a String with length greater than 0, therefore a truthy expression. You might be looking for

v-if=”[‘option1’, ‘option2’].indexOf(varName) > -1”

… which is equivalent to

v-if=”varName === ‘option1’ || varName === ‘option2’”

…where varName is the variable holding whatever you have put in the var - which needs renaming (to varName or any other name of the choice, except a reserved word).

Avoid using loose comparisons at all costs. (Use === instead of ==). They open the door to extremely difficult to trace bugs. It’s way better to cast the variables to a particular type then to allow them to have multiple types of values.
It is considered good practice to use computed properties or methods when the condition becomes long (a good rule of thumb is: when you need more than 2 operands, use a computed/method).
Computed properties are used when you don’t need to pass in any arguments while methods allow passing arguments (i.e.: the current item inside a v-for).

Solution 2:

I needed to list var twice (as follows). It is now working as desired.

<div v-if=”var==’option1’||var==’option2’” class=”…
<div>…
</div>
</div>

[Vue.js] VueJS Updating data based on query variable

In my route there is a parameter like: ?id=101

And there is some data like:

data () {
return {
record: {id: null}
}
}

Now, what to do this: if the query parameter is present, to update the id in the data with the id in the query variable. I tried doing this in the fetch, as follows:

async fetch ({ store, redirect, params, query }) {
this.record = {id: query.id}
}

However, nothing happens. I also tried calling a function from the fetch, but it says the method was not defined.

Can you please help?

Solution :

Ok my answer got deleted. Find the answer below:

export default {
data () {
return {
record: {
id: null
}
}
},
created () {
this.fetchData()
},
watch: {
‘$route’: ‘fetchData’
},
methods: {
fetchData () {
getRecord(this.$route.query.id, (err, id) => {
if (err) {
this.error = err.toString()
} else {
this.record.id = id
}
})
}
}
}

More info here:

https://router.vuejs.org/guide/advanced/data-fetching.html

[Vue.js] Vue.js Component emit

there is some problem about component $emit

This is my child component:

<template>
<div class=”input-group mb-3 input-group-sm”>
<input v-model=”newCoupon” type=”text” class=”form-control” placeholder=”code”>
<div class=”input-group-append”>
<button class=”btn btn-outline-secondary” type=”button” @click=”addCoupon”>comfirm</button>
</div>
</div>
</template>
<script>
export default {
props: [“couponcode”],
data() {
return {
newCoupon: this.couponcode
};
},
methods: {
addCoupon() {
this.$emit(“add”, this.newCoupon);
}
}
};
</script>

This is parent component

<template>
<div>
<cartData :couponcode=”coupon_code” @add=”addCoupon”></cartData>
</div>
</template>

<script>
import cartData from “../cartData”;
export default {
components: {
cartData
},
data() {
return {
coupon_code: “”
}
},
methods:{
addCoupon() {
const api = `${process.env.API_PATH}/api/${
process.env.CUSTOM_PATH
}/coupon`;
const vm = this;
const coupon = {
code: vm.coupon_code
};
this.$http.post(api, { data: coupon }).then(response => {
console.log(response.data);
});
},
}
}
</script>

When I click the ‘confirm’ buttonthe console.log display ‘can’t find the coupon’ If I don’t use the componentit will work

What is the problem? It’s about emit?

Solution :

addCoupon() {
this.$emit(“add”, this.newCoupon); // You emitted a param
}
// then you should use it in the listener
addCoupon(coupon) { // take the param
const api = `${process.env.API_PATH}/api/${
process.env.CUSTOM_PATH
}/coupon`;
const coupon = {
code: coupon // use it
};
this.$http.post(api, { data: coupon }).then(response => {
console.log(response.data);
});
},

[Vue.js] VueJS disable any global css and allow only scoped CSS in component

Is it possible to disable all global CSS inside a VueJS component in order to allow only scoped CSS in the component ? If yes, how ?

The problem I’m trying to solve is detailed below.

* {
margin: 0 auto;
padding: 0;
text-align: center;
color: black;
font-family: tahoma;
}

.items ul {
padding-top: 20px;
position: relative;
}

/* Make all children “inline” */
.items li {
/*float: left;*/
display: inline-block;
text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;
}

/* Add horizontal connector. Note: they are 2 pseudo-elements */
.items li::before, .items li::after {
content: ‘’;
position: absolute;
top: 0;
right: 50%;
width: 55%;
height: 42px;
z-index: -1;
border-top: 1px solid #CCC;
}

.items li::after {
border-left: 1px solid #CCC;
left: 50%;
right: auto;
}

/* Remove left and right connector from a single child */
.items li:only-child::after, .items li:only-child::before {
display: none;
}

.items li:only-child {
padding-top: 0;
}

/* Remove “outer” connector */
.items li:first-child::before, .items li:last-child::after {
border: 0 none;
}
/* Add back the down connector for last node */
.items li:last-child::before {
border-right: 1px solid #CCC;
border-radius: 0 5px 0 0;
}

/* Add curve line to the first child’s connector */
.items li:first-child::after {
border-radius: 5px 0 0 0;
}

/* Add down connector from parent */
.items ul ul::before {
content: ‘’;
border-left: 1px solid #CCC;
z-index: -1;
height: 20px;
position: absolute;
top: 0px;
left: 50%;
width: 0;
}

/* Add cosmetic for each item */
.items li a {
font-size: 12px;
background-color: white;
border: 1px solid #CCC;
padding: 5px 10px;
height: 14px;
text-decoration: none;
display: inline-block;
border-radius: 4px;
}

/* Change bg-color while hovering each item */
.items li a:hover {
background-color: #EEF;
}

/* EXPERIMENTAL for multiple parents */
/* Add margin for the parents */
.items li a:not(:only-of-type) {
position: relative;
margin-bottom: 16px;
}

/* Add “down” connector (vertical line) from each multi-parent, EXCEPT the last one */
.items li > a:not(:last-of-type)::after{
content: ‘’;
position: absolute;
border-left: 1px solid #CCC;
border-bottom: 1px solid #CCC;
top: 20px;
width: 75%;
height: 20px;
left: 50%;
z-index: -1;
}

/* Special case for the last multiple-parent, using border-right */
.items li > a:not(:only-of-type):last-of-type::after {
content: ‘’;
position: absolute;
border-right: 1px solid #CCC;
border-bottom: 1px solid #CCC;
top: 20px;
width: 50%;
height: 20px;
right: 50%;
z-index: -1;
border-bottom-right-radius: 5px;
}

/* Give the curve line to the first multiple parent …. */
.items li > a:not(:only-of-type):first-child::after {
border-bottom-left-radius: 5px;
}

/* The middle element of multi-parents*/
.items li > a:not(:first-child):not(:last-of-type)::before {
content: ‘’;
position: absolute;
border-bottom: 1px solid #CCC;
top: 40px;
width: 50%;
right: 50%;
z-index: -1;
}

.items ul:last-of-type li {
padding-left: 0;
padding-right: 0;
}
<div class=”items”>
<ul>
<li>
<a href=”#”>Dagon</a>
<a href=”#”>Veil of Discord</a>
<a href=”#”>Other Parent Item</a>
<ul>
<li>
<a href=”#”>Null Talisman</a>
<ul>
<li><a href=”#”>Circlet</a></li>
<li><a href=”#”>Mantle of Intelligence</a></li>
<li><a href=”#”>Recipe: Null Talisman</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

This code comes from https://jsfiddle.net/sangprabo/o8dda3um/23/

But I get some css perturbation coming from Laravel global CSS, like shown in the image below, this is why I’d like to disable any CSS causing these perturbation.

Solution :

I finally fixed it by adding this in my component’s CSS:

<style lang=”css” scoped>
*, *::before, *::after {
box-sizing: content-box;
}

</style>

[Vue.js] What am I doing wrong on Vue.js?

I’m new on vue.js but I can not understand why it still says { title } instead Hello world!

new Vue({
el:’#app’,
data: {
title:”Hello World!”
}
});
<html>
<head>
<title></title>
</head>
<body>
<div id=”#app”>
{ title }
</div>
<script src=”/script.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
</body>
</html>

I can not understand what is wrong but I’m just copying and pasting from tutorial

Solution :

You have to remove the # in <div id=”#app”>

Here is the full code :

new Vue({
el:’#app’,
data:
{
title:”Hello World!”
}
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
</head>
<body>
<div id=”app”>
<p> { title } </p>
</div>
<script src=”script.js”></script>
</body>
</html>
<html>

Solution 2:

# means id, you don’t need to put id=”#app”, that’s repetitive.

Besides that, you should load vue.js before you use new Vue.

<html>
<head>
<title></title>
</head>
<body>
<div id=”app”>
{ title }
</div>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<script>
new Vue({
el:’#app’,
data() {
return {
title: “Hello World”
}
}
});
</script>
</body>
</html>

[Vue.js] HTTP request blocked by CORS for not having Access-Control-Allow-Origin header but the header is present

when using Python with Flask and have created a REST api, I need my vue.js app to interact with it and get data, but I get No ‘Access-Control-Allow-Origin’ header is present.

when adding that header from nginx (so i can proxy the API as development server does not have any option to allow cross-origin access) I’ve tried to use jQuery instead of vue-resource and that worked.

nginx config:

server {
listen 5089;
access_log off;
error_log /dev/null crit;
location / {
add_header ‘Access-Control-Allow-Headers’ ‘content-type’;
add_header ‘Access-Control-Allow-Origin’ ‘*‘;
proxy_pass http://localhost:5000;
proxy_read_timeout 90;
}
}

vue.js Component:

<template>
<div id=”app”>
<div id=”nav”>
<router-link to=”/“ class=”btn-dark”>Home</router-link>
|
<router-link to=”/about”>About</router-link>
</div>
<label>User ID:
<input type=”text” v-model=”auth.id” required/>
</label>
<label>
Password:
<input type=”text” v-model=”auth.password”/>
</label>
<button v-on:click.prevent=”getToken”>Submit</button>
</div>
</template>
<script>
export default {
data () {
return {
auth: {
id: ‘’,
password: ‘’
}
}
},
methods: {
getToken: function (token) {
this.$http.post(‘http://localhost:5089/auth', {
UID: this.auth.id,
pass: this.auth.password
}).then(function (data) {
console.log(data)
})
}
}
}
</script>

API route code:

@app.route(‘/auth’, methods=[‘POST’])
def authenticate():
print(request.form)
for data in request.form:
try:
jsonParsed = json.loads(data)
id = jsonParsed[‘UID’]
allegedPass = jsonParsed[‘pass’]
except Exception:
return jsonify({
‘message’: ‘Oopsie Whoopsie what a nice cat, look’
})
if id and allegedPass:
authFile = open(‘auth.json’, ‘r’)
authData = json.load(authFile)
authFile.close()
try:
hashedPass = authData[str(id)][‘pass’]
except Exception:
return jsonify({
‘message’: ‘Oopsie Whoopsie look, a foxie’
})
if hashedPass == allegedPass:
token = jwt.encode({‘id’: id, ‘pass’: allegedPass, ‘exp’: datetime.utcnow() + timedelta(minutes=15)},
app.config[‘secret’])
return jsonify({
‘token’: token.decode(‘UTF-8’)
})
else:
return jsonify({
‘message’: ‘GTFO’
})
else:
return jsonify({
‘message’: ‘Kill yourself already.’
})

It should send a token back to the App but instead I get the following error in console:

POST http://localhost:5089/auth 500 (INTERNAL SERVER ERROR)
Access to XMLHttpRequest at ‘http://localhost:5089/auth' from origin ‘http://localhost:8080' has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

On the API terminal I get:

127.0.0.1 - - [06/Apr/2019 09:24:13] “OPTIONS /auth HTTP/1.0” 200 -
ImmutableMultiDict([])
127.0.0.1 - - [06/Apr/2019 09:24:13] “POST /auth HTTP/1.0” 500 -

Traceback (most recent call last):
.
.
.
File “/home/sids/Projects/laboratory/py/server.py”, line 58, in authenticate
if id and allegedPass:
UnboundLocalError: local variable ‘id’ referenced before assignment

Solution :

It turns out that the vue-resource module was not sending data properly or it was not being received properly; so when I was trying to parse the request form, there was an error which caused the issue and the browser presumed that the Origin was blocked despite knowing otherwise; however, when using jQuery now; that works

[Vue.js] Keeping two arrays of objects separate in VueJS?

there is two arrays of objects:

data: {
a: [{“name”:null}],
b: [{“name”:null}]
},

And there is two methods. The first method adds an object to ‘a’. And the second method, copies the entire ‘a’ to ‘b.

methods: {
addNametoA() {
this.a.push({“name”:null})
},
CopyAtoB() {
this.b = this.a
}
}

The problem is that once CopyAtoB() method is triggered, then whenever I add an object to a, it automatically copies it to b as well. This should not happen and how can I avoid it from happening?

Here is a jsbin showing this behavior.

https://jsbin.com/dojicasuqo/1/edit?html,js,console,output

Solution :

You are using the same array in both cases. You’re passing a reference and not making a copy of the array.

You need to copy the array in CopyAToB(). Something like this:

this.b = […this.a]

Solution 2:

You can indeed do what Radu Di was doing. However, the object inside the array is still getting referenced.

See example.

You should use below instead. To achieve complete unreferenced Object/Array.

copyAToBWithJson(){
this.b = JSON.parse(JSON.stringify(this.a));
}

[Vue.js] How to fix 'Cannot read property '_wrapper' of undefined' error when using webpack with Vue?

I use axios to get information from DB. I get response from server in array:

My html tags:

Js code looks like this:

data() {
return {
departments: {
id: 0,
name: “name of company”,
nameZod: “name of company dif”
},
};
},
created() {
axios
.get(‘/SomeController/Departments’)
.then(response => {
this.departments = response.data;
console.log(this.departments);
})
}

I get an error: Cannot read property ‘_wrapper’ of undefined. Its very strange cause I use similar code in other module and its work correctly.

Solution :

you just need to initiate the departments as an array like this:

data() {
return {
departments: [
{
id: 0,
name: “name of company”,
nameZod: “name of company dif”
},
],
};
},

[Vue.js] How do I move a component object to a global object?TrackAudio Player

when currently working on a music player, there is a “tracks” component that retrieves an ajax request that displays a list of songs. onClick there is that song data go into an object that when attempting to send to a component that is completely unrelated which is the audio player. What is the best way to send this data to the audio player?

Track

<template>
<div id=”tracks”>
<h5 class=”header”>Top tracks</h5>

<select name=”range” v-model=”range”>
<option value=”day”>Day</option>
<option value=”week”>Week</option>
<option value=”month”>Month</option>
<option value=”year”>Year</option>
<option value=”life”>Life</option>
</select>
<br>
<div id=”top-tracks”>
<div id=”track” v-for=”(track) in tracks” :key=’track.id’>
<img @click=”currentTrack(track)” class=”cover” :src=”‘https://api.napster.com/imageserver/v2/albums/' + track.albumId + ‘/images/500x500.jpg’”>

<div class=content-name><p>{track.name}</p></div>
<div class=”artist-name”><p>{track.artistName}</p></div>
</div>
</div>

</div>
</template>

<script>
import axios from ‘axios’;

export default {
name: ‘Tracks’,
components: {
},
data () {
return {
tracks: [],
track: {
name: “”,
artist: “”,
album: “”,
song: “”
},
range: ‘day’
}
},
created() {
this.trackData();
},
watch: {
range : function () {
this.trackData();
}
},
methods: {
trackData: function () {
axios.get(‘http://api.napster.com/v2.2/tracks/top?apikey=YTkxZTRhNzAtODdlNy00ZjMzLTg0MWItOTc0NmZmNjU4Yzk4&limit=10&range=' + this.range)
.then(response => {
// JSON responses are automatically parsed.
this.tracks = response.data.tracks
})
.catch(e => {
this.errors.push(e)
})
},
currentTrack: function (track) {
this.track.name = track.name;
this.track.artist = track.artistName;
this.track.album = track.albumId;
this.track.song = track.href;

}
}
}
</script>

Audio Player

<template>
<div id=”audio-player”>
<div class=”player__inner”>

<current-track class=”player__left”/>

<div class=”player__center”>
<player-controls/>
<player-playback/>
</div>

<div class=”player__right”>
<!– <device-picker/> –>
<!– <volume-bar/> –>
</div>
</div>
</div>
</template>

<script>
import CurrentTrack from ‘./CurrentTrack’;
import PlayerControls from ‘./PlayerControls’;
import PlayerPlayback from ‘./PlayerPlayback’;

export default {
name: “audio-player”,
components: {
CurrentTrack,
PlayerControls,
PlayerPlayback
},
data () {
return {

}
}
}
</script>

Solution :

As the application grows larger and more complex, Vuex will be great to use, but it also introduces concepts such as mutations and actions, which could need some time to wrap the head around. The easier way to achieve what you want is to set the root component’s data. Simply set the data property of the root vue.js component and retrieve it with this.$root.$data. The code will be something like this:

new Vue({

data: {
user: …
}
})