혼합에서 Vue 인스턴스에 액세스하는 방법
나는 이러한 종류의 논리를 구현하고 싶다.this.$store.value
로컬 데이터로 이동합니다.예를 들어 pages/index.vue에서는 이렇게 합니다.
method: {
this.value = this.$store.value
}
다른 로직이 있어서 페이지를 몇 장 사용하고 있기 때문에 믹스인에 기입하고 싶습니다.
그런데 어떻게 접속해야 할지 모르겠어요.this
(VueInstnce) mixins?
mixin은 컴포넌트의 코드보다 먼저 실행되며 mixin은 Vue에 의해 컴포넌트 인스턴스에 바인드(머지)되므로 컴포넌트/인스턴스 범위에서 mixin에 쉽게 액세스 할 수 있지만 그 반대의 경우는 지원되지 않습니다.
고객의 요구를 충족시키기 위해 믹스인 방식(예:created
(예를 들어) 컴포넌트의 인스턴스에 대한 참조를 파라미터로 하여 실행해야 하는데, 이와는 다릅니다.
단, 필요한 것을 실행하도록 코드를 재구성한 경우instance
.created
mixin의 메서드 및 데이터에 액세스하여 인수를 전달할 수 있습니다.
var mixin = {
data: {mixin: 'mixin'},
created: function () {
console.log('mixin hook called')
},
methods: { test: function(arg){console.log(arg); } }
};
vm=new Vue({
data: {component: 'component'},
mixins: [mixin],
created: function () {
console.log('called hook of ' + this.component + ' and accessing ' + this.mixin)
},
});
vm.test(vm.mixin);
vm.test(vm.component); // no problem to run mixin's method with component's data
> mixin hook called
> called hook of component and accessing mixin
> mixin
> component
좋아요, 그래서 그게 나쁜 관행이라고 생각될지는 모르겠지만, 저는 단방향 데이터 전송에 성공했습니다.event bus
.
사용하고 있다vuejs 3
와 함께composition api
요건: 모든 컴포넌트가 앱 전체에 표시되는 글로벌 싱글톤 컴포넌트에 접근할 수 있어야 합니다.
plugin.js
- 여기에서는created
에서 일어나다.mixin
컴포넌트 인스턴스의 참조를 가져옵니다.아래 예에서는 항상 1개만 있습니다.tracker
컴포넌트 인스턴스(글로벌팝업).좀 더 복잡한 다른 시나리오가 있다면 이벤트 버스 솔루션을 사용하는 것이 좋습니다.
import Tracker from "@/plugins/ProgressTracker/components/Tracker.vue";
export default {
install(app, params = {}) {
app.component("tracker", Tracker);
let instance = undefined;
app.mixin({
created() {
if (this.$options.name === "ProgressTrackerPopup") {
instance = this;
}
},
});
const progressTracker = () => {
//
};
progressTracker.show = function () {
instance.show();
};
app.config.globalProperties.$progressTracker = progressTracker;
},
};
useProgressTracker.js
- 글로벌하게 재사용 가능한 컴포지터블 기능으로 노출show
방법
import { ref, computed, getCurrentInstance } from "vue";
export default function useProgressTracker() {
const internalInstance = getCurrentInstance();
const progressTracker = internalInstance.appContext.config.globalProperties.$progressTracker;
const show = () => {
progressTracker.show();
};
return {
show,
};
}
Tracker.vue
- 다른 컴포넌트에서 글로벌하게 접근해야 하는 컴포넌트(그 중 일부)name
중요합니다.다음 순서로 설정해야 합니다.mixin
컴포넌트 생성을 검출할 수 있습니다.
<template>
<div class="onTop" v-if="isShow">test</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "ProgressTrackerPopup",
setup() {
var isShow = ref(false);
const show = () => {
isShow.value = true;
};
return {
isShow,
show,
};
},
};
</script>
<style scoped>
.onTop{
position: absolute;
z-index: 1999;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #0000004f;
}
</style>
이게 그거다.플러그인을 등록하는 것을 잊지 마십시오.
import ProgressTracker from "@/plugins/plugin.js";
// ..
app.use(ProgressTracker, {});
팝업을 표시하려면 , 다음의 순서를 실행합니다.
// <tracker />
import useProgressTracker from "@/plugins/ProgressTracker/use/useProgressTracker.js";
const tracker = useProgressTracker();
tracker.show();
코드의 마지막 행은 기본적으로show
메서드를 사용할 수 있습니다.반면, 만약 당신이 user를 사용한다면event bus
대신 대상 컴포넌트 자체의 팝 이벤트에 가입했을 것입니다.
이 솔루션은 이벤트버스를 취급하고 싶지 않고 케이스가 비교적 사소한 경우(항상 글로벌인스턴스가 1개밖에 없는 경우)에 도움이 됩니다.단, 인스턴스 배열을 사용하여 순서대로 메서드를 루프 호출할 수 있습니다.:)
언급URL : https://stackoverflow.com/questions/53078211/how-to-access-vue-instance-from-mixins
'programing' 카테고리의 다른 글
네스트된 루트는 스태틱패스를 끊습니다 (0) | 2022.08.27 |
---|---|
pthreads mutex vs 세마포어 (0) | 2022.08.27 |
계산된 속성은 VueJ의 window.innerwidth에 반응합니다.s (0) | 2022.08.27 |
C 콘솔의 행을 읽는 방법 (0) | 2022.08.27 |
c (0) | 2022.08.27 |