Reputation: 14834
I want to pass BASE_URL
to all components. My App.js is like:
<template>
<router-view></router-view>
</template>
<script>
import addJoke from './components/addJoke.vue'
import showJokesAll from './components/showJokesAll.vue'
export default {
components: {
'add-joke': addJoke,
'show-jokes-all': showJokesAll
},
data () {
return {
BASE_URL : 'http://127.0.0.1:8090'
}
}
}
</script>
<style>
</style>
And the routes.js
:
import showJokesAll from './components/showJokesAll.vue';
import addJoke from './components/addJoke.vue';
export default [
{path:'/', component: showJokesAll, props: {BASE_URL: 'http://127.0.0.1:8090'} },
{path:'/add', component: addJoke, props: {BASE_URL: 'http://127.0.0.1:8090'} }
]
and in showJokesAll
component I have:
<script>
import axios from 'axios';
export default {
name: 'showJokesAll',
props: ['BASE_URL'],
data () {
return {
jokes:[]
}
},
methods: {
},
created() {
axios.get( BASE_URL + '/api/jokes').then( response => this.jokes = response.data);
}
}
</script>
But the components is not received BASE_URL
.
[Vue warn]: Error in created hook: "ReferenceError: BASE_URL is not defined"
How can I fix this?
Upvotes: 1
Views: 384
Reputation: 3289
You can write a Mixins file which contains data or a function which returns your BASE_URL and then import mixins file using,
import myMixins from './my_mixins.js'
Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.
If you want to manage the state of the data you should have a look at Vuex.
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
Updated:
Also have a look a Vue Instance Properties.
Upvotes: 1
Reputation: 23968
To access the prop define with props: ['BASE_URL'], you would use this.BASE_URL
:
axios.get( this.BASE_URL + '/api/jokes').then(/*...*/)
Upvotes: 2