Vuej에 전역 변수 적용
인스턴스화 시 Vue 컴포넌트에 글로벌하게 전달하고 싶은 javascript 변수를 가지고 있기 때문에 등록된 각 컴포넌트는 속성으로 가지고 있거나 글로벌하게 접근할 수 있습니다.
주의: vuej의 이 글로벌 변수를 읽기 전용 속성으로 설정해야 합니다.
예를 들어, 모든 컴포넌트가 글로벌에 액세스 할 수 있습니다.appName
한 줄의 코드만 쓰면 됩니다.
Vue.prototype.$appName = 'My App'
$
마법이 아니라 Vue가 모든 인스턴스에서 사용할 수 있는 속성에 사용하는 규칙입니다.
또는 모든 글로벌 메서드 또는 속성을 포함하는 플러그인을 작성할 수 있습니다.
글로벌 믹스인을 사용하여 모든 Vue 인스턴스에 영향을 줄 수 있습니다.이 혼합에 데이터를 추가하여 모든 vue 구성 요소에 값/값을 사용할 수 있도록 할 수 있습니다.
이 값을 읽기 전용으로 하려면 이 스택 오버플로 응답에서 설명된 방법을 사용합니다.
다음은 예를 제시하겠습니다.
// This is a global mixin, it is applied to every vue instance.
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
data: function() {
return {
get globalReadOnlyProperty() {
return "Can't change me!";
}
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalReadOnlyProperty = "This won't change it";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
In Root: {{globalReadOnlyProperty}}
<child></child>
</div>
CreateApp()을 사용하는 VueJS 3에서는app.config.globalProperties
다음과 같이 합니다.
const app = createApp(App);
app.config.globalProperties.foo = 'bar';
app.use(store).use(router).mount('#app');
변수를 다음과 같이 호출합니다.
app.component('child-component', {
mounted() {
console.log(this.foo) // 'bar'
}
})
문서: https://v3.vuejs.org/api/application-config.html#warnhandler
데이터가 반응하지 않는 경우 VueX를 사용할 수 있습니다.
mixin과 change var를 사용할 수 있습니다.
// This is a global mixin, it is applied to every vue instance
Vue.mixin({
data: function() {
return {
globalVar:'global'
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalVar}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalVar = "It's will change global var";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
In Root: {{globalVar}}
<child></child>
</div>
글로벌 변수를 Vuejs를 포함하여 다른 항목에 기록해서는 안 되는 경우Object.freeze
정지할 수 있습니다.Vue의 뷰 모델에 추가해도 고정은 해제되지 않습니다.또 다른 옵션은 오브젝트가 Vue가 아닌 글로벌하게 작성되도록 의도된 경우 Vuej에 오브젝트의 동결된 복사본을 제공하는 것입니다.var frozenCopy = Object.freeze(Object.assign({}, globalObject))
Vuex를 사용하여 모든 글로벌 데이터를 처리할 수 있습니다.
main.js 파일에서 다음과 같이 Vue를 Import해야 합니다.
import Vue from 'vue'
그런 다음 다음과 같이 main.js 파일에 글로벌 변수를 선언해야 합니다.
Vue.prototype.$actionButton = 'Not Approved'
글로벌 변수 값을 다른 컴포넌트에서 변경할 경우 다음과 같이 변경할 수 있습니다.
Vue.prototype.$actionButton = 'approved'
https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example
여러 성분에 변수를 사용하지만 글로벌 범위를 오염시키고 싶지 않은 경우.이 경우 각 사용자가 사용할 수 있도록 설정할 수 있습니다.Vue instance
정의함으로써Vue prototype
:
Vue.prototype.$yourVariable = 'Your Variable'
이 행을 추가한 후 다음을 작성하십시오.Vue instance
프로젝트의 시작점에서는 대부분의 경우main.js
, 이제$yourVariable
모두 이용 가능합니다.Vue instances
「작성 전」입니다.다음 중 하나:
new Vue({
beforeCreate: function() {
console.log(this.$yourVariable)
}
})
★★★★★★★★★★★★★★★."Your Variable"
솔에기!!!!!!!
문서: https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example
불변으로 방식인 스태틱 방식을 할 수 .Object.defineProperty()
:
Object.defineProperty(Vue.prototype, '$yourVariable', {
get() {
return "Your immutable variable"
}
})
으로는 이 을 사용하면 가 ""에서 .Vue prototype
더 않은 를 사용할 수 .Object.freeze()
:
Object.defineProperty(Vue.prototype, '$yourVariable', {
get() {
return Object.freeze(yourGlobalImmutableObject)
}
})
in main.displays(또는 기타 js 파일)
export const variale ='someting'
app.vue 컴포넌트의 app(또는 다른 컴포넌트)에서
import {key} from '../main.js' (file location)
데이터 방식에서 변수에 대한 키를 정의하고 사용합니다.
변수는 글로벌하기 때문에 index.html로 선언할 수 있습니다.javascript 메서드를 추가하여 변수 값을 반환할 수 있으며, 읽기 전용입니다.나는 그렇게 했다.
2개의 글로벌 변수(var1 및 var2)가 있다고 가정합니다.index.html 헤더에 다음 코드를 추가합니다.
<script>
function getVar1() {
return 123;
}
function getVar2() {
return 456;
}
function getGlobal(varName) {
switch (varName) {
case 'var1': return 123;
case 'var2': return 456;
// ...
default: return 'unknown'
}
}
</script>
각 변수에 대해 방법을 수행하거나 매개 변수를 사용하여 단일 방법을 사용할 수 있습니다.
이 솔루션은 서로 다른 vuejs 믹스인 간에 작동하며 매우 글로벌한 가치를 제공합니다.
언급URL : https://stackoverflow.com/questions/40896261/apply-global-variable-to-vuejs
'sourcecode' 카테고리의 다른 글
수집되지 않은 참조 오류: photoModule이 정의되지 않았습니다. (0) | 2022.08.03 |
---|---|
정규식을 사용하여 여러 줄 텍스트 일치 (0) | 2022.08.03 |
구성 요소 렌더링 함수의 무한 업데이트 루프 (0) | 2022.08.03 |
Android에서 strings.xml 문자열의 굵은 글씨체 (0) | 2022.08.01 |
Laravel Nova - 리소스의 인덱스 보기 다시 로드 (0) | 2022.08.01 |