简体   繁体   中英

How to pass props to all routes in vue.js?

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?

要使用 props: ['BASE_URL'] 访问 prop 定义,您可以使用this.BASE_URL

axios.get( this.BASE_URL + '/api/jokes').then(/*...*/)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM