[英]How to pass props to all routes in vue.js?
I want to pass BASE_URL
to all components.我想将
BASE_URL
传递给所有组件。 My App.js is like:我的 App.js 就像:
<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
:还有
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:在
showJokesAll
组件中我有:
<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
.但是组件没有收到
BASE_URL
。
[Vue warn]: Error in created hook: "ReferenceError: BASE_URL is not defined"
[Vue 警告]:创建钩子时出错:“ReferenceError:未定义 BASE_URL”
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,您可以编写一个包含数据的Mixins文件或返回 BASE_URL 的函数,然后使用导入 mixins 文件,
import myMixins from './my_mixins.js'
Mixins are a flexible way to distribute reusable functionalities for Vue components.
Mixin 是一种为 Vue 组件分发可重用功能的灵活方式。 A mixin object can contain any component options.
mixin 对象可以包含任何组件选项。 When a component uses a mixin, all options in the mixin will be “mixed” into the component's own options.
当组件使用 mixin 时,mixin 中的所有选项都会“混合”到组件自己的选项中。
If you want to manage the state of the data you should have a look at Vuex .如果你想管理数据的状态,你应该看看Vuex 。
Vuex is a state management pattern + library for Vue.js applications.
Vuex 是 Vue.js 应用程序的状态管理模式 + 库。 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 .也看看Vue Instance Properties 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.