반응형
Chrome 확장의 공유 vuex
첫 번째 질문:
크롬 확장으로 다음과 같은 설정을 하고 있습니다.
- vuex 저장소에 써야 하는 콘텐츠 스크립트
- 해당 저장소를 초기화하는 백그라운드 스크립트
- 스토어에서 내용을 렌더링하는 팝업 스크립트(콘텐츠 스크립트로부터 수신)
store.js
import Vue from "vue";
import Vuex from "vuex";
import "es6-promise/auto";
import createMutationsSharer from "vuex-shared-mutations";
import dummyData from "./dummyData";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
chromePagesState: {
allSections: [],
},
},
mutations: {
setChromePagesState(state, value) {
state.chromePagesState = value;
},
addWhiteListedItem(state, item) {
state.chromePagesState.allSections[0].itemSectionCategory[0].tasks.splice(
0,
0,
item
);
},
},
actions: {
// init from local storage
async loadChromePagesState({ commit }) {
const json = await getStorageValue("inventoryData");
commit(
"setChromePagesState",
Object.keys(json).length === 0 && json.constructor === Object
? dummyData
: JSON.parse(JSON.stringify(json))
);
},
// send message to background script to call init (shortened)
async loadChromePagesStateBrowser({ commit }) {
browser.runtime
.sendMessage({ type: "storeinit", key: "chromePagesState" })
.then(async (chromePagesState) => {
const json = await getStorageValue("inventoryData");
commit(
"setChromePagesState",
Object.keys(json).length === 0 && json.constructor === Object
? dummyData
: JSON.parse(JSON.stringify(json))
);
});
},
},
// stuff from vuex-shared-mutations
plugins: [
createMutationsSharer({
predicate: [
"addWhiteListedItem",
"loadChromePagesState",
"loadChromePagesStateBrowser",
],
}),
],
});
vue 컴포넌트의 콘텐츠스크립트 호출 저장:
index.js
import store from "../popup/firstpage/store";
new Vue({
el: overlayContainer,
store,
render: (h) => h(Overlay, { props: { isPopUp: isPopUp } }),
});
Overlay.vue
<script>
import { mapState, mapMutations } from "vuex";
export default {
props: ["isPopUp"],
data() {
return {
};
},
computed: mapState(["chromePagesState"]),
methods: {
...mapMutations(["addWhiteListedItem"]),
// this gets called in the template
addToWhiteList() {
let newItem = initNewItemWithWebPageData();
this.addWhiteListedItem(newItem);
},
},
}
</script>
백그라운드 스크립트는 메시지를 수신하고 스토어에서 변환을 호출합니다.
background.js
import store from "../content/popup/firstpage/store";
browser.runtime.onMessage.addListener((message, sender) => {
if (message.type === "storeinit") {
store.dispatch("loadChromePagesState");
return Promise.resolve(store.state[message.key]);
}
});
오픈시popup.js
에 메시지를 송신하는 스토어 변환이 호출됩니다.background.js
스토어의 다른 돌연변이를 호출합니다.
popup.js
import store from "./firstpage/store";
export function showPopup() {
const popupContainer = document.createElement("div");
new Vue({
el: popupContainer,
store,
render: (h) => h(App),
created() {
console.log("Calling store dispatch from popup");
this.$store.dispatch("loadChromePagesStateBrowser");
},
});
}
어디에App.vue
이
<template>
<div id="app">
<OtherComponent />
</div>
</template>
<script>
import { mapActions } from "vuex";
import OtherComponent from "./components/ChromePage.vue";
export default {
name: "App",
OtherComponent: {
VueTabsChrome,
},
methods: {
...mapActions(["loadChromePagesState"]),
},
mounted() {
// once fully mounted we load data
// this is important for a watcher in ChromePage component
console.log("App.vue mounted");
// this.loadChromePagesState();
},
};
</script>
default new를 직관적으로 내보내면 Import할 때마다 새 인스턴스가 생성되므로 스크립트 간에 동기화되지 않습니다(스토어가 서로 다른 개체이기 때문입니다).
어떻게 하면 동일한 스토어를 한 번 초기화하여 여러 진입점에서 사용할 수 있습니까?
popup.js
는 사용자가 확장 아이콘을 클릭하면 열립니다.
(이 경우 [new]탭을 클릭합니다).
언급URL : https://stackoverflow.com/questions/68930294/shared-vuex-in-chrome-extension
반응형
'programing' 카테고리의 다른 글
JNI 콜이 느려지는 이유는 무엇입니까? (0) | 2022.07.16 |
---|---|
모델 인스턴스의 VueJs 워처와 여러 이벤트 리스너 (0) | 2022.07.16 |
비트 시프트와 덧셈만을 사용하여 어떻게 곱하고 나눌 수 있습니까? (0) | 2022.07.16 |
Vuex에서 여러 돌연변이를 호출하는 적절한 방법 (0) | 2022.07.16 |
Java 실행자: 작업이 완료되었을 때 차단 없이 알림을 받으려면 어떻게 해야 합니까? (0) | 2022.07.16 |