1 2 3 4 5 6 7
| app.config.globalProperties.foo = 'bar'
app.component('child-component', { mounted() { console.log(this.foo) } })
|
添加可以在应用程序内的任何组件实例中访问的全局 property。属性名冲突时,组件的 property 将具有优先权。
这可以代替 Vue 2.x Vue.prototype
扩展:
1 2 3 4 5 6
| Vue.prototype.$http = () => {}
const app = Vue.createApp({}) app.config.globalProperties.$http = () => {}
|
官方文档:https://www.vue3js.cn/docs/zh/api/application-config.html#globalproperties
值得注意的是:而在3.0的settup中是没有this的!!!
1 2 3 4 5 6 7 8
| import { getCurrentInstance,onBeforeMount} from 'vue'; setup (props,context) { const { ctx } = getCurrentInstance(); onBeforeMount(()=>{ ctx.$http.get('/getData').then().catch(err => {console.log(err)}) }); ....... }
|