vue3.0でのglobalPropertiesの定義と、セットアップでのglobalPropertiesによって定義されたフィールドの使用法

序文:

vue3.0        のグローバル定義プロパティ値は2.0とは異なりglobalPropertiesを   使用し、これの使用法と 比較します。+ 2.0でプロパティ名マウントでき、3.0の使用方法が異なりますはい、ここに要約があります

目次:

1つ、2.0

main.js

ページ上:

2、3.0

main.js

ページ上:

1.マウント済み(2.0と同じ)ですが、マウント済みは3.0ではほとんど使用されません

2.セットアップ(ハイライト)

(1)ctxを使用しますが、テスト後、distにパッケージ化した後、ctxの下の値は使用できず、ローカルで使用できます。

(2)プロキシを使用する(強くお勧めします)

画像を表示するローカルデバッガー:

プロキシ

ctx

3.公式説明:入場

globalProperties


1つ、2.0

main.js

import api from './api' // 导入api接口
Vue.prototype.$api = api
Vue.prototype.$abc = 111

ページ上:

this.$api.user...

let abc = this.$abc   //111

2、3.0

main.js

const app = createApp(App)
//全局配置
app.config.globalProperties.foo = 'bar'

ページ上:

1.マウント済み(2.0と同じ)ですが、マウント済みは3.0ではほとんど使用されません

let abc = this.foo //bar

2.セットアップ(ハイライト)

(1)ctxを使用しますが、テスト後distにパッケージ化した後、ctxの下の値は使用できず、ローカルで使用できます。

(2)プロキシを使用する(強くお勧めします)

 setup() {
     const { proxy, ctx } = getCurrentInstance()
     const showMessage = () => {
      let m = proxy.foo 
      let n = ctx.foo
      ElMessage.success({
        message: 'proxy: '+m, //本地和打包出来都可以拿到
        type: 'success'
      })
      ElNotification({
        title: 'ctx: '+n, //打包出来以后,内容拿不到
      })
    }
    return {
      showMessage
    }
}

画像を表示するローカルデバッガー:

プロキシ

ctx

3.公式説明:入場

globalProperties

  • タイプ[key: string]: any

  • デフォルトundefined

  • 使用法

app.config.globalProperties.foo = 'bar'

app.component('child-component', {
  mounted() {
    console.log(this.foo) // 'bar'
  }
})

 

アプリケーション内の任意のコンポーネントインスタンスでアクセスできるグローバルプロパティを追加します。プロパティ名が競合する場合、コンポーネントのプロパティが優先されます。

これにより、Vue2.xVue.prototype 拡張機能を置き換えることができます 

// 之前(Vue 2.x)
Vue.prototype.$http = () => {}

// 之后(Vue 3.x)
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

 

 

おすすめ

転載: blog.csdn.net/qq_41619796/article/details/114284535