programing

Vuex 모듈에 상태를 내부적으로 관리하는 복잡한 개체를 추가합니다.

javaba 2022. 7. 17. 12:26
반응형

Vuex 모듈에 상태를 내부적으로 관리하는 복잡한 개체를 추가합니다.

Vuex를 상태 핸들러로 사용하고 있으며 반드시 부자일 필요는 없는 컴포넌트 간에 데이터를 공유하는 도구로 사용하고 있습니다.

Vuex를 사용하여 외부 라이브러리에서 가져온 복잡한 객체를 공유하고 싶습니다.이 개체에는 속성을 변경하는 메서드가 있습니다.

이 객체의 경우 상태를 중앙 집중화하는 것이 아니라 컴포넌트 간에 공유할 수 있는 방법을 원합니다.

다른 해결 방법을 생각했습니다(및 폐기). - strict 모드를 비활성화합니다.하지만 다른 모든 경우에 사용할 수 있기를 바랍니다. 매우 유용합니다! - Vuex는 사용하지 마십시오.그러나 매우 편리하고 디버깅툴(크롬 플러그인 등)과 잘 통합되어 있습니다.Vuex를 보다 단순한 스토어 https://austincooper.dev/2019/08/09/vue-observable-state-store로 바꿉니다.이전과 같은 문제

그렇다면, 다른 라이브러리의 복잡한 데이터를 공유하는 가장 좋은 방법은 무엇일까요?vuex를 사용하고 싶은데 가장 깨끗한 솔루션을 찾을 수 없습니다!

문제의 예: (get more items를 누르면 콘솔 오류가 나타납니다.)https://codepen.io/ale-grosselle/pen/dyyxyMr

class Item{
    id;
    constructor(i){
        this.id = Math.round(i * 100);
    }
}
//Share collection between the different components
class Collection {
    items;
    constructor(){
        this.items = [new Item(Math.random())];
    }   
    getMore(){
        const randomVal = (Math.random());
        this.items.push(new Item(randomVal));
    }
}
const store = new Vuex.Store({
    strict: true,
    state: {
        collection: new Collection()
    },
    mutations: {},
    getters: {
        collection(state) {
            return state.collection
        }
    },     
    modules: {}
})

new Vue({
    el: '#app',
    store,
    computed: {
        collection() {
            return this.$store.getters.collection;
        }
    },
    methods: {
        addNew() {
            this.collection.getMore();
        }
    }
})

Vuex를 사용하여 어플리케이션을 통해 객체를 공유하려는 이유는 이해하지만, 어플리케이션을 통해 단일 데이터 소스를 공유하는 것이 목적이며, 이를 (정확히) 원하지 않는다고 정확하게 말하고 있기 때문에 그 목적은 아니라고 생각합니다.

필요에 따라 모듈에 의해 내보낸 Collection 클래스의 싱글톤인스턴스를 공유하고 Provid/Inject API를 사용하여 응용 프로그램을 통해 액세스할 수 있습니다.

(프로젝트에서 거의 같은 작업을 시도했기 때문에) 다른 문제는 스토어 상태를 시리얼화할 수 있어야 한다는 것입니다.특별한 처리를 하지 않으면 Chrome DevTools에서 "시간 여행"을 사용하면 컬렉션 메서드가 손실됩니다(JSONify/string을 사용하여 상태가 시리얼화 및 역직렬화되므로).JSON.parse)

그게 당신이 원하는 게 아니라는 건 알지만, Vuex는 당신이 원하는 상황이 아닌 것 같아요.

편집: 위에서 설명한 아이디어를 사용하여 예제를 업데이트하고 Vue.observable을 사용하여 개체를 Vue에 대해 반응하게 했습니다. 여기서 확인할 수 있습니다.

class Item {
    id;
    constructor(i){
        this.id = Math.round(i * 100);
    }
}

//Share collection between the different components
class Collection {
    items;
    constructor(){
        this.items = [new Item(Math.random())];
    }   
    getMore(){
        const randomVal = (Math.random());
        this.items.push(new Item(randomVal));
    }
}

// Make it observable
const collection = Vue.observable(new Collection());

// Export like a singleton from some module
// export default collection

// provide anywhere on top, for example, in the app itself.
new Vue({
    el: '#app',
    provide: {
        'collection': collection
    },
})

// inject anywhere "below" and use it
const ChildComponent = Vue.component('child-component', {
    template: `
        <button @click='addNew'>Get more items</button>
    `,
    inject: ['collection'],
    methods: {
        addNew() {
            this.collection.getMore();
        }
    }
});

// template
<div id='app'>
    <pre>{{ collection }}</pre>
    <div v-for='item in collection.items'>
        {{ item.id }}
    </div>
    <child-component />
</div>

언급URL : https://stackoverflow.com/questions/59071673/add-in-a-vuex-modules-a-complex-object-which-manages-its-status-internally

반응형