programing

Vue.js 앱의 vuex 스토어를 사용하여 하위 구성 요소(설정 페이지)에서 값을 설정하는 방법은 무엇입니까?

luckcodes 2022. 8. 11. 22:12

Vue.js 앱의 vuex 스토어를 사용하여 하위 구성 요소(설정 페이지)에서 값을 설정하는 방법은 무엇입니까?

선택한 값을 저장소에 저장하여 다른 모든 구성 요소가 해당 값을 사용하여 모양을 변경할 수 있도록 하는 "설정" 구성 요소를 만들려고 합니다.

[설정]vue:

설정 중 하나(코드펜에서도 확인할 수 있음)

[...]

<p>{{ themeColor }}</p>
<v-radio-group v-model="themeColor">
  <v-radio label="light" value="light"></v-radio>
  <v-radio label="dark" value="dark"></v-radio>
</v-radio-group>

[...]

<script>
export default {
  data () {
    return {
      // default value
      themeColor: 'light',
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.themeColor
    }
  },
  methods: {
    changeThemeColor() {
      this.$store.commit('changeThemeColor')
    },
  }
}
</script>

이 설정의 선택된 값을 스토어에 올바르게 송신하는 방법을 모르기 때문에 메서드로 변환(기본값의 필요성 등)을 작성했을 뿐입니다.themeColor: 'light'위와 같이 좀 더 헷갈리게 해주세요.)

저장/모듈/설정.js

const state = {
    themeColor: ''
  }
  
  const mutations = {
    changeThemeColor: state => {
      state.themeColor = ''
    }
  }
  
  export default {
    state,
    mutations
  }
  

이 값을 모든 컴포넌트에 사용할 수 있도록 하려면 어떻게 해야 합니까?

이런 걸 써야 하나요?getters또는actions잘 모르겠어요

https://vuex.vuejs.org/en/forms.html,에서 getter와 setter를 사용하여 계산된 속성을 사용합니다.

export default {
  computed: {
    themeColor: {
      get () {
        return this.$store.state.themeColor
      },
      set (value) {
        this.$store.commit('changeThemeColor', value)
      }          
    }
  }
}

주의해 주세요.data또는methods.


당신의 가게는 또한 더 닮아야 한다.

const state = {
  themeColor: 'light' // default value
}

const mutations = {
  changeThemeColor (state, themeColor) {
    state.themeColor = themeColor
  }
}

데모 ~ https://codepen.io/anon/pen/YYbPww?editors=1011


를 표시/읽고 싶은 경우themeColor컴포넌트 상태, 도우미 사용을 권장합니다.

import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState(['themeColor'])
}

언급URL : https://stackoverflow.com/questions/48412978/how-to-set-values-from-a-child-component-settings-page-using-vuex-store-in-a-v