账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Vuex: 怎样在父子模块间传递信息?
    21
    0

    假设我有一个这样结构的Vuex store:

    window.st = new Vuex.Store({
      modules: {
        people: {
          namespaced: true,
          state: { name: "user" },
          mutations: {
            name: (state, value) => (state.name = value)
          },
          modules: {
            age: {
              namespaced: true,
              state: { value: 0 },
              mutations: {
                value: (state, value) => (state.value = value),
                // if name changes, reset age value
                ["???"]: state => (state.value = 0)
              }
            },
            gender: {
              namespaced: true,
              state: { value: "unknown" },
              mutations: {
                value: (state, value) => (state.value = value),
                // if name changes, reset gender value
                ["???"]: state => (state.value = "unknown")
              }
            }
          }
        }
      }
    });

    Fiddle(请按F12,result frame,window.st): https://jsfiddle.net/liqi0816...

    root
     people: { name }
      age: { value }
      gender: { value }

    这个结构实际上存在依赖,agegender依赖于people。如果people变了的话,agegender至少要重置到未初始化的状态。现在的问题就是,上面代码中"???"的地方该怎么写呢?试了一下../这样的写法,并不支持。

    这是一个简化了的问题,实际项目中的agegender都很庞大,所以没法取消namespaced……还是说本来就不应该用module?

    再进一步,如果people是动态注册上来的,没法预先知道people的路径名的话,又该怎么做?

    谢谢大家

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 念你如初↓ 普通会员 1楼

      Vuex 是一个用于管理状态的库,它允许你在一个应用中管理多个状态,这些状态可能来自不同的组件或者服务。在Vuex中,父子模块之间的信息传递可以通过组件的通信来实现。

      以下是一种常见的实现方式:

      1. 组件通信:子组件可以通过 props 将数据传递给父组件。父组件可以将这些数据保存在一个状态中,并通过一个函数来触发子组件。

      ```javascript // 子组件 class ChildComponent extends Vue { // 子组件需要的props props: { message: String }

      // 子组件的更新函数 methods: { sendMessage() { this.$store.dispatch('childMessage', 'Hello, world!'); } } }

      // 父组件 import ChildComponent from './ChildComponent.vue';

      new Vue({ el: '#app', data: { childMessage: 'Hello, world!' }, components: { ChildComponent }, methods: { sendMessage() { this.$store.dispatch('parentMessage', this.childMessage); } } }); ```

      1. 使用 Vuex 的 action 和 mutations:Vuex 提供了 action 和 mutation 两个主要的事件。action 是一组方法,这些方法可以被多个组件共享。mutation 是一组数据操作,它们只在需要时被触发。

      ```javascript // action export function parentMessage(state: any) { state.childMessage = 'Hello, world!'; }

      export function childMessage(state: any) { state.childMessage = 'Hello, world!'; }

      // mutation export function sendMessage() { this.$store.dispatch('parentMessage', this.childMessage); } ```

      在这些例子中,我们使用了 action 和 mutation 来在子组件和父组件之间传递信息。在子组件中,我们调用了 action 并在需要时修改了 state。在父组件中,我们调用了 mutation 并在需要时更新了 state。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部