【问题标题】:Mutating Nuxt Component变异 Nuxt 组件
【发布时间】:2021-09-20 01:10:38
【问题描述】:

我已经尝试学习 vuex 好几个星期了(我已经看过几十个教程,它们只是通过反例)。我很慢,仍然无法掌握如何做到这一点。
我的想法是能够在组件之间切换选项卡。我知道我应该使用一个动作来激活突变(我无法做到),但我认为突变应该仍然可以在按下按钮时起作用?

我的问题是如何正确设置在单击按钮时传递组件值的突变?
另外我想知道我的组件切换想法是否可行,或者是否有更好的方法。

SignUp.vue

<template>
  <keep-alive>
    <component :is="component" />
  </keep-alive>
</template>

<script>
import SignUpOne from "../components/SignUpOne.vue"
import SignUpTwo from "../components/SignUpTwo.vue"
import SignUpThree from "../components/SignUpThree.vue"

export default {
components: {
    SignUpOne,
    SignUpTwo,
    SignUpThree,
  },
  computed: {
    ...mapState([
      'component',
    ])
  },
}
</script>

store/index.js

export const state = () => ({
  component: "SignUpOne",
})

export const mutations = () => ({
  changePage(state, payload) {
    state.component = payload.value;
  }
})

SeperateComponent.vue

<template>
  <button @click="changePg">Button</button>
</template>

<script>
export default {
  methods: {
    changePg() {
      this.$store.commit({
        type: 'changePage',
        value: "SignUpTwo"
       });
    },
  },
}
</script>

【问题讨论】:

  • 嗨,为什么你需要 Vuex 来做标签? Vuex 应该用作全局/广泛状态管理的存储。如果是标签,这可能应该保留为本地状态。
  • 我希望能够从其中的组件切换选项卡。我想如果我在本地拥有所有三个按钮组件,那将不是问题,但我无法让它们与组件进行通信。我认为我可能应该刚刚发出。再次感谢

标签: nuxt.js mutation-events vue-dynamic-components


【解决方案1】:

你需要这样的东西

SignUp.vue

<script>
import { mapState } from 'vuex'
export default {
...

store/index.js

...

export const mutations = () => ({
  CHANGE_PAGE(state, newComponentName) {
    state.component = newComponentName;
  }
})

export const actions = () => ({
  updateComponentName({ commit }, componentName) {
    commit('CHANGE_PAGE', componentName)
  },
})

SeperateComponent.vue

<template>
    <div>
      <button @click="updateComponentName('SignUpOne')">Button</button>
      <button @click="updateComponentName('SignUpTwo')">Button</button>
      <button @click="updateComponentName('SignUpThree')">Button</button>
    </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions(['updateComponentName']),
  },
}
</script>

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2021-06-02
    • 2019-05-11
    • 2021-08-17
    • 2021-09-24
    • 1970-01-01
    • 2021-07-30
    • 2021-09-18
    • 2019-03-09
    相关资源
    最近更新 更多