link411 link412 link413 link414 link415 link416 link417 link418 link419 link420 link421 link422 link423 link424 link425 link426 link427 link428 link429 link430 link431 link432 link433 link434 link435 link436 link437 link438 link439 link440 link441 link442 link443 link444 link445 link446 link447 link448 link449 link450 link451 link452 link453 link454 link455 link456 link457 link458 link459 link460 link461 link462 link463 link464 link465 link466 link467 link468 link469 link470 link471 link472 link473 link474 link475 link476 link477 link478 link479 link480 link481 link482 link483 link484 link485 link486 link487 link488 link489 link490 link491 link492 link493 link494 link495 link496 link497 link498 link499 link500 link501 link502 link503 link504 link505 link506 link507 link508 link509 link510 link511 link512 link513 link514 link515 link516 link517 link518 link519 link520 link521 link522 link523 link524 link525 link526 link527 link528 link529 link530 link531 link532 link533 link534 link535 link536 link537 link538 link539 link540 link541 link542 link543 link544 link545 link546 link547

[Vue.js] Is it possible to use Vuex mapActions inside an exported module Subscribe to RSS

Is it possible to call Vuex mapActions from a separate module that’s imported into a component?

I’m trying to standardize a set of functions in a vue.js web app. I’d like to import them into each component and pass some values the to function operate. I’m using vuex to manage state. Currently each component calls these functions each time they’re loaded (identically the same).

I’d like to refactor into this into one module and import it into each component as needed. This code uses mapActions as part of it’s function. Below are the relevant pieces of code: component, module, vuex action

vue.js component:

//the imported function call
if (!this.queued){
timer.updatePage(this.pagination, this.orders);
}

the module code (advance.js):

import { mapActions } from ‘vuex’;

let currentComp = {
name: ‘purchase’,
date: null,
start: false
}

const timer = {
…mapActions([‘currentComponent’]),
updatePage(pagination, order) {
currentComp.name = ‘nextComponent’;
this.currentComponent(currentComp);
}
}
export default timer;

the vuex code:

//in the actions section:
currentComponent({
commit
}, comp) {
console.log(comp);
commit(‘setCurrentComponent’, comp);
}

//in the mutations section:
setCurrentComponent: (state, comp) => {
state.currentComponent = comp.name;
return state;
}

when the component runs the imported function i get:

vuex.esm.js?2f62:870 Uncaught TypeError: Cannot read property ‘dispatch’ of undefined
at Object.mappedAction [as currentComponent] (vuex.esm.js?2f62:870)
at eval (advance.js?935c:37)

when i remove the this from this.currentComponent i get:

advance.js?935c:37 Uncaught ReferenceError: currentComponent is not defined
at eval (advance.js?935c:37)

thanks in advance for any guidance.

Solution :

mapActions is a shortcut for creating a method that looks something like this

currentComponent() {
this.$store.dispatch(‘xxx’)
}

When you call this function, the this context is timer. Since timer does not have a $store property, you get the error Cannot read property ‘dispatch’ of undefined. The quickest way to get around this would be to change the this context to the component which does have a $store property. You could do this by passing the component as a third property in updatePage and binding currentComponent to the function.

// component code
timer.updatePage(this.pagination, this.orders, this);

// advance.js
const timer = {
…mapActions([‘currentComponent’]),
updatePage(pagination, order, component) {
currentComp.name = ‘nextComponent’;
this.currentComponent.bind(component)(currentComp);
}
}

I’d recommend using a mixin for this type of behavior though.

import { mapActions } from ‘vuex’;

let currentComp = {
name: ‘purchase’,
date: null,
start: false
}

const timerMixin = {
methods: {
…mapActions([‘currentComponent’]),
updatePage(pagination, order) {
currentComp.name = ‘nextComponent’;
this.currentComponent(currentComp);
}
}
}
export default timerMixin;

In the component, import the timerMixin and register it as a mixin. Those methods would then be available directly on the component and you can call them with a small tweak to the existing code.

if (!this.queued){
this.updatePage(this.pagination, this.orders);
}

[Vue.js] VueJS new values to props getting pushed instead of reset Subscribe to RSS

I’ve got a problem with my VueJS project. I made a GoogleMaps Component within a DetailView.vue. The maps component uses three props like driver, waypoints and stopOver.

The project structure is:
App.vue.js containts Login.vue.js with a route to the main Dashboard View.
Inside this MainView, there is some menu elements like ‘Tours’ with a DataTable inside.

Clicking on the datatable row, VueJS presents a DetailView.vue.js inside a v-dialog (using Vuetify).

Inside this DetailView theres another datatable, a switch and at the top, my map component.

<LiefermaxMap style=”width: 100%; height: 50%;” :waypoints=”waypoints” :driver=”driverLocation” :stopOver=”showCalculatedTour”></LiefermaxMap>

waypoints and driverLocation are computed properties, showCalculatedTour is a regular property, depending on the state of the switch.

Closing this Detailvue.js Dialog and opening another tour results in pushing another set of waypoints (and driverLocation too) to the property instead of replacing the old ones.

waypoints() {
var points = [];
if (!this.showCalculatedTour) {
this.loadnoSpecific.items.items.forEach(element => {
var p = { lat: element.latitude, lng: element.longitude, done: element.done };
points.push(p);
});
} else {
this.data.contracts.forEach(element => {
var c = element.customer.position;
var p = { lat: c.lat, lng: c.lng, done: element.done }
points.push(p);
});
}
console.log(‘points: ‘ + points)
return points;
},
driverLocation() {
const drv = this.data.location;
const marker = { lat: drv.latitude, lng: drv.longitude };
return marker;
},

Heres a screenshot of the project.

What I’m doing wrong?

UPDATE:

Expected behavior: remove all the other waypoints from the previous selected tours
Actual behavior: waypoints are added to the old ones

Tours.vue.js Example (the view behind the dialog in the screenshot):

<template>
<div>
<v-toolbar flat color=”white”>
<v-toolbar-title>Touren</v-toolbar-title>
<v-spacer></v-spacer>
</v-toolbar>
<v-data-table style=”width: 70vw;”
:headers=”headers”
:items=”tours.items.items”
:rows-per-page-items=”[5,10,20,50,100]“
:loading=”isLoading”
:total-items=”totalItems”
:must-sort=”true”
:pagination.sync=”pagination”
class=”elevation-1”
\>
<template slot=”items” slot-scope=”props”>
<tr @click=”rowClicked(props.item)”>
<td class=”text-xs-left”>{ props.item.loadno }</td>
<td class=”text-xs-left”>{ props.item.tourname }</td>
<td class=”text-xs-left”>{ props.item.kfz }</td>
<td class=”text-xs-left”>{ props.item.driverID }</td>
<td class=”text-xs-left”>{ props.item.device }</td>
<td class=”text-xs-left”>{ props.item.created_at | formatDate }</td>
</tr>
</template>
</v-data-table>
<v-dialog v-model=”showDetail” transition=”dialog-bottom-transition” max-width=”70vw”>
<TourDetail v-model=”showDetail” :data=”selectedTour” style=”height: 90vh;”></TourDetail>
</v-dialog>
</div>
</template>

<script>
import { settings } from ‘../settings’;
import { authHeader } from ‘../_helpers’;
import TourDetail from ‘./TourDetail.vue’;
export default {
name: ‘tours’,
components: {
TourDetail
},
data() {
return {
totalItems: 0,
selectedTour: {},
showDetail: false,
pagination: {
descending: true,
page: 1,
rowsPerPage: 10,
sortBy: ‘loadno’
},
headers: [ // .. ]
};
},
watch: {
pagination(newValue, oldValue) {
this.getDataFromApi();
},
tours(newValue, oldValue) {
this.totalItems = newValue.items.total;
}
},
mounted() {
this.getDataFromApi();
},
computed: {
tours() {
return this.$store.state.tours.all;
},
isLoading() {
return this.$store.state.tours.loading;
}
},
methods: {
rowClicked(tour) {
const requestOptions = {
method: ‘GET’,
headers: authHeader()
};
const loadno = tour.loadno;
console.log(‘LoadNo: ‘ + loadno);
this.$store.dispatch(‘locations/getLoadnoSpecific’, { loadno });
fetch(
`${settings.apiUrl}/tours/loadno/complete/` + loadno,
requestOptions
).then(response =>
response.json().then(json => {
this.selectedTour = json.tour;
this.showDetail = true;
})
);
},
getDataFromApi() {
const perpage = this.pagination.rowsPerPage;
const page = this.pagination.page;
const sortby = this.pagination.sortBy;
const descending = this.pagination.descending;

this.$store.dispatch(‘tours/getAll’, {
perpage,
page,
sortby,
descending
});
}
}
};
</script>

TourDetail.vue

<template>
<v-flex style=”height: 100%;”>
<v-toolbar
color=”primary”
dark
flat
style=”z-index: 2; position: absolute;”
\>
<v-toolbar-title class=”justify-center”>Fahrer: { data.driver.firstname + ‘ ‘ + data.driver.lastname }   |   iPad: { data.device }   |   Fahrzeug: { data.kfz }</v-toolbar-title>
</v-toolbar>
<v-card style=”height: 100%; position: relative;”>
<LiefermaxMap style=”width: 100%; height: 50%;” :waypoints=”waypoints” :driver=”driverLocation” :stopOver=”showCalculatedTour”></LiefermaxMap>
<v-layout row wrap style=”height: 50%;”>
<v-flex xs12>
<v-card style=”height: 100%;”>
<v-switch v-model=”showCalculatedTour” :label=”switchLabel” style=”position: absolute; right: 10%;”></v-switch>
<v-data-table
:headers=”headers”
:items=”data.contracts”
:expand=”expand”
:rows-per-page-text=”perPageText”
style=”padding: 5%;”
\>
<template slot=”items” slot-scope=”props”>

</template>
<template slot=”expand” slot-scope=”props”>
<v-card>
<div>

</div>
</v-card>
</template>
</v-data-table>
</v-card>
</v-flex>
</v-layout>
</v-card>
</v-flex>
</template>

<script>
import LiefermaxMap from ‘../components/LiefermaxMap.vue’;
export default {
components: {
LiefermaxMap
},
computed: {
loadnoSpecific() {
return this.$store.state.locations.loadnoSpecific;
},
waypoints() {
var points = [];
if (!this.showCalculatedTour) {
this.loadnoSpecific.items.items.forEach(element => {
var p = { lat: element.latitude, lng: element.longitude, done: element.done };
points.push(p);
});
} else {
this.data.contracts.forEach(element => {
var c = element.customer.position;
var p = { lat: c.lat, lng: c.lng, done: element.done }
points.push(p);
});
}
console.log(‘points: ‘ + points)
return points;
},
driverLocation() {
const drv = this.data.location;
const marker = { lat: drv.latitude, lng: drv.longitude };
return marker;
},
switchLabel() {
return this.showCalculatedTour ? ‘errechnete Route’ : ‘gefahrene Route’;
}
},
props: [‘data’],
data() {
return {
showCalculatedTour: false,
googleWaypoints: [],
drivenWaypoints: [],
expand: false,
perPageText: ‘pro Seite’,
completeTourLoading: true,
completeTour: [{}],
selectedContract: {},
headers: [… ]
};
},
methods: { … }
}
};
</script>
<style scoped>
// …
</style>

And LiefermaxMap component:

<template>
<div v-show=”mapInitialized” class=”liefermaxmap” id=”liefermaxmap” ref=”liefermaxmap”></div>
</template>
<script>
export default {
name: ‘LiefermaxMap’,
props: [‘waypoints’, ‘driver’, ‘stopOver’],
data: function() {
return {
mapName: ‘liefermaxmap’,
markerCoordinates: [{}],
mapInitialized: false,
directionsService: null,
directionsDisplay: null,
vueGMap: null,
bounds: null,
markers: []
};
},
watch: {
waypoints(newValue, oldValue) {
console.log(‘Waypoints changed, count: ‘ + newValue.length);
console.log(newValue)
this.setWaypoints();
}
},
methods: {
createGoogleMaps: function() {
return new Promise((resolve, reject) => {
let gmap = document.createElement(‘script’);
gmap.src =
https://maps.googleapis.com/maps/api/js?key=XXXX';
gmap.type = ‘text/javascript’;
gmap.onload = resolve;
gmap.onerror = reject;
document.querySelector(‘head’).appendChild(gmap);
});
},
initGoogleMaps: function() {
const localOptions = {
zoom: 4,
center: this.driver,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
},
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: false,
streetViewControl: false,
streetViewControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};

this.vueGMap = new google.maps.Map(
this.$refs[‘liefermaxmap’],
localOptions
);
// eslint-disable-next-line
var drivermarker = new google.maps.Marker({
position: new google.maps.LatLng(this.driver),
map: this.vueGMap,
icon: ‘http://maps.google.com/mapfiles/ms/micons/truck.png'
});
this.directionsService = new google.maps.DirectionsService();
this.directionsDisplay = new google.maps.DirectionsRenderer();
this.directionsDisplay.setMap(this.vueGMap);
this.mapInitialized = true;
},
addMarker(latLng, color) {
let url = ‘http://maps.google.com/mapfiles/ms/icons/';
url += color + ‘-dot.png’;

let marker = new google.maps.Marker({
map: this.vueGMap,
position: latLng,
icon: {
url: url
}
});
},
setWaypoints() {
this.directionsService = new google.maps.DirectionsService();
this.directionsDisplay = new google.maps.DirectionsRenderer();
this.directionsDisplay.setMap(this.vueGMap);
var googleWaypoints = [];
this.waypoints.forEach(element => {
var pos = new google.maps.LatLng(element.lat, element.lng);
var wp = { location: pos, stopover: false };
googleWaypoints.push(wp);
console.log(element)
if (element.done == true) {
this.addMarker(pos, ‘green’)
} else {
this.addMarker(pos, ‘red’)
}
});

var i = 0;
var j = 0;
var temparray = [];
var chunk = 15;

for (i = 0, j = googleWaypoints.length; i < j; i += chunk) {
temparray = googleWaypoints.slice(i, i + chunk);
var request = {
origin: ‘XXX’,
destination: ‘XXX’,
travelMode: ‘DRIVING’,
optimizeWaypoints: true,
waypoints: temparray
};
this.directionsService.route(request, (result, status) => {
if (status === ‘OK’) {
this.directionsDisplay.setDirections(result);
console.log(result);
}
});
}
},
googleMapsFailedToLoad() {
this.vueGMap = ‘Error while loading map’;
}
},
mounted() {
this.initGoogleMaps();
}
};
</script>
<style scoped>
.liefermaxmap {
width: 100%;
height: 100%;
}
</style>

Solution :

vue.js reuses components - use key to force mounting

Change

<LiefermaxMap style=”width: 100%; height: 50%;” :waypoints=”waypoints” :driver=”driverLocation” :stopOver=”showCalculatedTour”></LiefermaxMap>

to

<LiefermaxMap style=”width: 100%; height: 50%;” :key=”waypoints” :waypoints=”waypoints” :driver=”driverLocation” :stopOver=”showCalculatedTour”></LiefermaxMap>

use key to tell vue.js not to reuse the component - so mounted can be triggered,

or move the initMap method.

[Vue.js] How to use the slot bottom-row in b-table component in bootstrap-vue? Subscribe to RSS

there is a component that uses bootstrap-vue.js b-table component. I need to make a result row, which will be the sum of each column. But when I try to use a bottom-row as a thead-top, then the bottom-row fills only the first column, ignoring the rest. How to make it work like a thead-top?

<b-table
:items=”items”
:fields=”fields”
responsive=”sm”
\>
<template slot=”thead-top” slot-scope=”data”>
<tr>
<th colspan=”2”> </th>
<th>Type 1</th>
<th colspan=”3”>Type 2</th>
<th>Type 3</th>
</tr>
</template>
<template slot=”bottom-row”
slot-scope=”data”
\>
<tr>
<th colspan=”2”> </th>
<th>Type 1</th>
<th colspan=”3”>Type 2</th>
<th>Type 3</th>
</tr>
</template>
</b-table>

Solution :

I realized what I was doing wrong. Tag is not needed in template slot=”bottom-row”.

<template slot=”bottom-row”
slot-scope=”data”
\>
<td v-for=”(field, i) in data.fields”>
{ i }
</td>
</template>

[Vue.js] how to render array stored in vuex Subscribe to RSS

when trying to render array of objects stored in store in the form of cards. But, when not able to. Since it shows typeError.
It states

“error in render: “TypeError: Cannot read property ‘item’ of undefined”

I tried using this keyword and shifting the code to mounted() hook.
But, the error keeps on showing.

Here is the code:
CardRenderer.vue:

<template lang=”html”>

<div>
<b-container class=”bv-example-row”>
<b-row v-for=”(row, i) in this. rows” v-bind:key=”i”>
<b-col v-for=”(item, j) in row” v-bind:key=”j” >

<!– you card –>
<b-card
:title=”item.title”
img-src=”item.icon”
img-alt=”Image”
img-top
tag=”article”
style=”max-width: 20rem;”
class=”mb-2”
\>
<b-card-text>
<h1>{item.name}</h1>
<pre>{item.description}</pre>
</b-card-text>
<b-button :href=”‘/dashboard/‘+this.item.name” variant=”primary”>More</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</div>

</template>

<script lang=”js”>
export default {
name: ‘CardRenderer’,
props: {

},
data() {
return {
// rows: []
}
},
mounted() {

},

methods: {

},
computed: {
rows() {
const itemsPerRow = 3
var rows = []
let arr = this.$store.getters.responseAPI.apps
// eslint-disable-next-line
console.log(arr)
for (let i = 0; i < arr.length; i += itemsPerRow){
let row = []
for (let z = 0; z < itemsPerRow; z++) {
row.push(arr[z])
}
rows.push(row)
}

// eslint-disable-next-line

// console.log(this.rows)
return rows[0]
}

}
}
</script>

<style scoped>

</style>

This is how the error looks like.

and this is how the rows object looks like

How do i remove the error and the render the card.

I would love to have the changed code as the answer.
Thanks :)

Solution :

I think you have a mistake at the computed property return statement.

Try replacing return rows[0] to return rows to return an array instead of the first item :)

I’ve finally caught an error))
This is my code sample at sandbox: https://codesandbox.io/embed/vue-template-sm0yx

You’ve got a mistake at the template, just remove this from :href=”‘/dashboard/‘+this.item.name” to make it look like this: :href=”‘/dashboard/‘+item.name”

That should work!))

[Vue.js] accesing data objects in vuejs Subscribe to RSS

there is a data() object in my Maincomponent.vue. In that data() there is an array called myDatabase and it has several objects. to access the fields in myDatabase using methods
to toggle the isPreview to false and true on click

data() {
return {

myDatabase: [
{
id: 1,
name: “Blue”,
fabric: require(“../static/images/blue.jpeg”),
previewImage: require(“../static/images/blue-shirt.jpeg”),
isPreview: true
},
{
id: 2,
name: “Black”,
fabric: require(“../static/images/black.jpeg”),
previewImage: require(“../static/images/black-shirt.jpeg”),
isPreview: false
}

]
}
},

methods: {
showPreview: function() {
return this.myDatabase.isPreview == false ? true : false
}
}

Solution :

Here is the documentation about methods :

Example :

<template>
<p>{ myDatabase[0].isPreview }</p>
<button @click=”reversePreview(1)”>Reverse preview</button>
</template>

<script>
export default {
data () {
return {
myDatabase: [{
id: 1,
name: “Blue”,
fabric: require(“../static/images/blue.jpeg”),
previewImage: require(“../static/images/blue-shirt.jpeg”),
isPreview: true
},
{
id: 2,
name: “Black”,
fabric: require(“../static/images/black.jpeg”),
previewImage: require(“../static/images/black-shirt.jpeg”),
isPreview: false
}]
}
},
methods: {
reversePreview (id) {
const index = this.myDatabase.findIndex(db => db.id === id)
this.myDatabase[index].isPreview = !this.myDatabase[index].isPreview
}
}
}
</script>

[Vue.js] How to distinguish between a prop and a method with the same name, in Vue? Subscribe to RSS

I recently switched from React to Vue. In React, i often had a method in a child component, that would look something like this:

onClick = (e)=>{
const val = e.target.value;
this.props.onClick(val)
}

I see that vue.js is very “free”, and allows you to treat component methods and props as “the same thing”.

Is there some way to distinguish between the two, like with this.props? What is the convention regarding this issue?

Solution :

You should take advantage of another vue.js technique, instead of passing a function, using its event emitter system:

// MyComponent:
methods: {
onClick(e) {
const val = e.target.value;
this.emit(‘click’, val);
}
}

<button @click=”onClick”>Click me</button>

//When you actually use the component

<MyComponent @click=”() => { console.log(‘delegated onClick!’); }”/>

Solution 2:

Props, data, computed properties and methods end up as properties on vue.js instance - members may also include lifecycle hooks when a component is declared as a class. As with any other class, their names may collide.

In case there are members that are private (onClick method) and are parts of public API (onClick prop), they can be named differently, e.g. with underscore naming convention that is common in JS OOP:


props: {
onClick: Function
},
methods: {
_onClick() {…}
}

The use of naming conventions for private properties is suggested by vue.js style guide.

Solution 3:

As mentioned in one of the comments try to avoid using duplicate names for props, methods, etc…

[Vue.js] Module parse failed Unexpected character '@' (1 0) vuejs , vuetify and vuex Subscribe to RSS

getting error while adding/integrating Vuetify like.. import Vuetify from ‘vuetify/lib’ Vue.use(Vuetify) in main.js

Error:

ERROR in ./node_modules/vuetify/src/stylus/components/_grid.styl
Module parse failed: Unexpected character ‘@’ (1:0)
You may need an appropriate loader to handle this file type.
| . @import ‘../bootstrap’

main.js

import Vuetify from ‘vuetify/lib’
Vue.use(Vuetify)

Solution :

we need to configure loader in webpack (webpack.config.js or webpack.js or webpack.base.js) like

webpack.base.js

…….other config

module: {
rules: [
{
test: /\.styl$/,
loader: [‘css-loader’, ‘stylus-loader’]
},

…..other loaders
]
}

….other config

to install loaders

npm i stylus-loader css-loader –save-dev

[Vue.js] baseURL remain localhost after deploy Nuxt App? Subscribe to RSS

there is developed a app using Nuxt( VueJS ). For api when created a route /api.

app.use(‘/api’, routes);

For implementing the api to fornt-end there is used just /api/the route

this.$axios.$get(“/api/order/order-details/“ + this.orderId).then(res => {
console.log(“res: “, res);
});

I never used any base url.. it automatically getting the baseURL as localhost: and he port

But after deploy its remain the same baseURL.. It should be my domain name.

How can I change the base URL in NUXT..

Solution :

As far as I know axios should get the base url dynamically, but you can also provide it a baseUrl yourself.
NuxtJS explains this themselves quite well in their documentation.

Read about env variables on the NuxtJS env docs.
Read about configuration on the NuxtJS configuration docs.

In short:

In the nuxt.config.js you add a baseUrl option like so:

// nuxt.config.js
export default {
env: {
baseUrl: process.env.BASE_URL || ‘http://localhost:3000'
}
}

Now you can use this config when creating the axios instance:

// plugins/axios.js
import axios from ‘axios’

export default axios.create({
baseURL: process.env.baseUrl
})

Then, in the pages, you can import axios like this: import axios from ‘~/plugins/axios’.

[Vue.js] What do /deep/ and shadow mean in a CSS selector? Subscribe to RSS

In looking at Polymer, I see the following CSS selector in the Styles tab of Chrome 37’s developer tools:

I’ve also seen a selector with pseudo selector ::shadow.

So, what do /deep/ and ::shadow in a CSS selector mean?

Solution :

As Joel H. points out in the comments, Chrome has since deprecated the /deep/ combinator, and it gives a syntax error in IE.

HTML5 Web Components offer full encapsulation of CSS styles.

This means that:

styles defined within a component cannot leak out and effect the rest of the page
styles defined at the page level do not modify the component’s own styles

However sometimes you want to have page-level rules to manipulate the presentation of component elements defined within their shadow DOM. In order to do this, you add /deep/ to the CSS selector.

So in the example shown, html /deep/ [self-end] is selecting all elements under the html (top level) element that have the self-end attribute, including those buried inside web components’ shadow DOMs roots.

If you require a selected element to live within a shadow root, then you can use the ::shadow pseudo selector on its parent element.

Consider:

<div>
<span>Outer</span>

#shadow-root
<my-component>
<span>Inner</span>
</my-component>
</div>

The selector html /deep/ span will select both <span> elements.

The selector ::shadow span will select only the inner <span> element.

Read more about this in the W3C’s CSS Scoping Module specification.

[Vue.js] Cross origin problem in vue.js application Subscribe to RSS

when new to Vue.js and when trying to build a simple iTunes search application in Vue.js. when trying to call the api with the code below but when having a CORS problem:

Access to fetch at ‘https://itunes.apple.com/search?term=drake' from origin ‘http://localhost:8080' has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves the needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The component code so far is:

<template>
<div class=”jumbotron”>
<h1 class=”display-4”>{title}</h1>
<p class=”lead”>{intro}</p>
<hr class=”my-4”>
<form class=”col-6 mr-auto ml-auto”>
<input class=”form-control form-control-lg mb-3” type=”search” placeholder=”Search” aria-label=”Search”>
<button class=”btn btn-success btn-lg btn-block mb-3” type=”submit” id=”SearchBtn”>Search</button>
<!–<router-link class=”btn btn-primary btn-lg btn-block” to=”/next”>Next</router-link>–>
</form>
</div>
</template>

<script>
export default {
name: “Hero”,
props: {
navLink: String
},
data: function() {
return {
title: “Simple Search”,
intro:
“This is a simple hero unit, a simple jumbotron-style.”,
subintro:
“It uses utility classes for typography and spacing to space content out.”
};
},
mounted: function() {
fetch(‘https://itunes.apple.com/search?term=drake')
.then(response => response.json())
.then(data => {
this.artist = data;
console.log(data);
})
}
};
</script>

<style>
.jumbotron {
margin-bottom: 0rem !important;
}
</style>

Any idea’s?

Solution :

Probably this works:

mounted: function() {
fetch(‘https://itunes.apple.com/search?term=drake',
{
‘Access-Control-Allow-Origin’: ‘*‘
})
.then(response => response.json())
.then(data => {
this.artist = data;
console.log(data);
})
}

else try implementing:

mounted: function() {
fetch(‘https://itunes.apple.com/search?term=drake',
{
headers: {
‘Access-Control-Allow-Origin’: ‘*‘,
‘Access-Control-Allow-Methods’: ‘POST, GET, PUT, OPTIONS, DELETE’,
‘Access-Control-Allow-Headers’: ‘Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type’,
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’
}
})
.then(response => response.json())
.then(data => {
this.artist = data;
console.log(data);
})
}