I am trying to pass the url of the domain where I am to pass it in axios. Here is my current hard url:
import axios from 'axios';
export default {
name: 'cart',
components: {},
data() {
return {
cart: '',
timer: '',
baseUrl: 'http://prestashop_1_6.local/modules/analyticsvuejs/php/cart.php',
}
},
methods: {
getCarts() {
axios
.get(this.baseUrl, {
params: {
action: 'cart'
}
})
.then(response => {
this.cart = response.data;
console.log(this.cart);
}, (error) => {
console.log(error);
}
)
},
},
created() {
this.getCarts();
this.timer = setInterval(this.getCarts, 5000)
},
}
and I'm trying to create a variable to dynamically pass it to all my components
I am looking to replace 'http: //prestashop_1_6.local/' with a dynamic variable.
Thank you for your help.
1) Create a separate file with a const containing this base url.
2) export this const
3) use it wherever you want
// consts.js
export const BASE_URL = 'http://prestashop_1_6.local';
// Any file that consume it.
import {BASE_URL} from './consts';
data() {
return {
url: `${BASE_URL}/something/something-else`
};
}
Related
I want to access query strings from url in nuxtjs page.
this is the page url with query strings -
http://localhost:3000/en-IN/atrsps/results/?pickupairport=Dubai&dropoffpoint=Bur%20Dubai,%20DU,%20United%20Arab%20Emirates&pickupdate=06%2F06%2F2021%2013%3A27
this is the my page script part
<script>
import axios from 'axios'
export default {
data() {
return {
cars: [],
loading: false,
disabled: true,
pickupairport: null,
dropoffpoint: null
}
},
asyncData({ route }) {
console.log(route.query)
},
computed: {
url() {
return `https://api.testdomain.com/V2/transfers/carlist?startpoint=${this.pickupairport}&endpoint=${this.dropoffpoint}&pickupdate=2021-07-01&pickuptime=14:55`
},
},
async created() {
await this.fetchData()
},
methods: {
async fetchData() {
this.loading = true //the loading begin
const res = await axios.get(this.url)
this.cars = res.data.response
this.loading = false
},
carsearch($state) {
setTimeout(() => {
axios
.get(this.url)
.then((res) => {
if (res.data.response.length > 1) {
res.data.response.forEach((item) => this.cars.push(item))
$state.loaded()
} else {
$state.complete()
}
})
.catch((err) => {
console.log(err)
})
}, 1000)
},
},
}
</script>
I want to pass pickupairport and dropoffpoint value from url to pickupairport & dropoffpoint in data.
in console, i can see this data
{
pickupairport: 'Dubai',
dropoffpoint: 'Bur Dubai, DU, United Arab Emirates',
pickupdate: '06/06/2021 13:27'
}
from the template you can access to it from $route object like $route.query and from the vue instance you can write this.$route.query
also you can check the $route object from vue dev tools. check out the picture below:
to pass the queries to data object you can just write:
data() {
return {
pickupairport: this.$route.query.pickupairport,
}
}
but you might not need to store the query in data object since you have access to $route object either from template or anywhere in your script
I am simply making an asynchronous request to get data about a MLB player but am failing to get new data by manually changing the query parameters in the URL. When I use watch, the from and the to are the same for some reason upon debugging with Vue dev tools. However, all works well when I manually click a link to navigate routes as the from and the to correctly represent the from and the to routes.
PitcherForm.vue
export default {
name: "PitcherForm",
components: {
PlayerForm,
},
watch: {
$route() {
this.handleSubmit({ firstName: this.$route.query.firstName, lastName: this.$route.query.lastName });
}
},
methods: {
handleSubmit: function(formValues) {
// this.$store.dispatch("fetchPlayer", { formValues, router: this.$router, player: "pitching" });
this.$store
.dispatch("fetchPlayer", { formValues, player: "pitching" })
.then((promiseObject) => {
console.log(promiseObject)
this.$router.push({
// name: 'PitcherData',
path: "pitching/player",
query: {
firstName: promiseObject.firstName,
lastName: promiseObject.lastName,
},
});
})
.catch((error) => {
console.log(error);
});
},
},
//store.js
import Vue from 'vue';
import Vuex from 'vuex';
import VuexPersist from 'vuex-persist';
import axios from 'axios';
Vue.use(Vuex);
// VuexPersist stuff
const vuexLocalStorage = new VuexPersist({
key: 'vuex',
storage: window.localStorage,
});
export const store = new Vuex.Store({
plugins: [vuexLocalStorage.plugin],
state: {
playerStats: []
},
// mutations, getters, excluded for convenience
actions: {
fetchPlayer({ commit }, data) {
return new Promise((resolve) => {
let firstName = data.formValues.firstName.replace(/\s/g, "").toLowerCase();
let lastName = data.formValues.lastName.replace(/\s/g, "").toLowerCase();
axios.get(`http://localhost:5000/${data.player}/player`,
{
params: {
first: firstName.charAt(0).toUpperCase() + firstName.slice(1),
last: lastName.charAt(0).toUpperCase() + lastName.slice(1),
},
}).then(response => {
commit('setPlayers', response.data);
}).catch((error) => {
console.log(error);
});
resolve({firstName, lastName});
});
}
}
});
Goal: Initially load posts using the Wordpress Rest API via Axios once in a Vue View, and only once during a session of visiting the Vue website.
Current Result: I currently fetch the results successfully and set them in sessionStorage. They display correctly. I want to know/learn if I am accomplishing this correctly and have the process optimized in the best way possible. I've looked up documentation and I think I have it down.
Current Code:
<script>
import Hero from "#/components/Hero.vue";
import axios from "axios";
export default {
name: "About",
components: {
Hero,
},
data: function() {
return {
eatery: [],
};
},
created() {
axios
.get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
.then((response) => {
sessionStorage.setItem("eatery", JSON.stringify(response.data));
})
.catch((error) => {
window.alert(error);
});
},
mounted() {
if (sessionStorage.getItem("eatery")) {
this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
}
},
};
</script>
I would check whether it's in the storage before trying to load it. In your case, it would look like this:
export default {
name: "About",
components: {
Hero,
},
data: function() {
return {
eatery: [],
};
},
loadEatery() {
axios
.get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
.then((response) => {
sessionStorage.setItem("eatery", JSON.stringify(response.data));
return response.data;
})
.catch((error) => {
console.error(error); // for debugging maybe
});
},
mounted() {
if (sessionStorage.getItem("eatery")) {
this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
} else {
loadEatery().then(data => this.eatery = data);
}
},
};
I want to use my component's data within my external JavaScript file, containing my Dropzone configuration. I tried unsuccessfully to use Function.prototype.bind:
export const dropzoneConfig = {
url: api.http.baseUrl + '/files',
thumbnailWidth: 150,
maxFilesize: 5,
acceptedFiles: 'image/*',
addRemoveLinks: true,
sending: function (file, xhr, formData) {
formData.append('type', 'photo');
},
success: function (file, xhr) {
file.id = xhr.data.id;
if (this.entry.files === undefined) {
this.entry.files = [];
}
this.entry.files.push(xhr.data);
this.saveNote();
}.bind(this),
headers: api.http.authHeaders().headers
};
In the code above, this.entry and this.saveNote are unavailable because they're from my Vue component. How do I make them accessible to the external file?
A more general solution would be for the component to pass in a success-event handler that has access to the component's data and methods, as shown below. This solution decouples the configuration from the component's internals.
dropzoneConfig.js:
export const dropzoneConfig = ({ onSuccess }) => ({
//...
success(file, xhr) {
//...
onSuccess(xhr.data)
}
})
App.vue:
<script>
import Dropzone from 'dropzone'
import { dropzoneConfig } from './dropzoneConfig'
export default {
data() {
return {
entry: {
files: []
}
}
},
created() {
Dropzone.options.myComponent = dropzoneConfig({
onSuccess: fileData => this.onDropzoneSuccess(fileData)
})
},
methods: {
saveNote() {
//...
},
onDropzoneSuccess(fileData) {
this.entry.files.push(fileData)
this.saveNote()
}
}
}
</script>
I'm would like to get titles for my pages dynamically in Nuxt.js in one place.
For that I've created a plugin, which creates global mixin which requests title from server for every page. I'm using asyncData for that and put the response into storage, because SSR is important here.
To show the title on the page I'm using Nuxt head() method and store getter, but it always returns undefined.
If I place this getter on every page it works well, but I would like to define it only once in the plugin.
Is that a Nuxt bug or I'm doing something wrong?
Here's the plugin I wrote:
import Vue from 'vue'
import { mapGetters } from "vuex";
Vue.mixin({
async asyncData({ context, route, store, error }) {
const meta = await store.dispatch('pageMeta/setMetaFromServer', { path: route.path })
return {
pageMetaTitle: meta
}
},
...mapGetters('pageMeta', ['getTitle']),
head() {
return {
title: this.getTitle, // undefined
// title: this.pageMetaTitle - still undefined
};
},
})
I would like to set title in plugin correctly, now it's undefined
Update:
Kinda solved it by using getter and head() in global layout:
computed: {
...mapGetters('pageMeta', ['getTitle']),
}
head() {
return {
title: this.getTitle,
};
},
But still is there an option to use it only in the plugin?
Update 2
Here's the code of setMetaFromServer action
import SeoPagesConnector from '../../connectors/seoPages/v1/seoPagesConnector';
const routesMeta = [
{
path: '/private/kredity',
dynamic: true,
data: {
title: 'TEST 1',
}
},
{
path: '/private/kreditnye-karty',
dynamic: false,
data: {
title: 'TEST'
}
}
];
const initialState = () => ({
title: 'Юником 24',
description: '',
h1: '',
h2: '',
h3: '',
h4: '',
h5: '',
h6: '',
content: '',
meta_robots_content: '',
og_description: '',
og_image: '',
og_title: '',
url: '',
url_canonical: '',
});
export default {
state: initialState,
namespaced: true,
getters: {
getTitle: state => state.title,
getDescription: state => state.description,
getH1: state => state.h1,
},
mutations: {
SET_META_FIELDS(state, { data }) {
if (data) {
Object.entries(data).forEach(([key, value]) => {
state[key] = value;
})
}
},
},
actions: {
async setMetaFromServer(info, { path }) {
const routeMeta = routesMeta.find(route => route.path === path);
let dynamicMeta;
if (routeMeta) {
if (!routeMeta.dynamic) {
info.commit('SET_META_FIELDS', routeMeta);
} else {
try {
dynamicMeta = await new SeoPagesConnector(this.$axios).getSeoPage({ path })
info.commit('SET_META_FIELDS', dynamicMeta);
return dynamicMeta && dynamicMeta.data;
} catch (e) {
info.commit('SET_META_FIELDS', routeMeta);
return routeMeta && routeMeta.data;
}
}
} else {
info.commit('SET_META_FIELDS', { data: initialState() });
return { data: initialState() };
}
return false;
},
}
}