【问题标题】:Get data from vuex store and select first option in variable从 vuex 存储中获取数据并选择变量中的第一个选项
【发布时间】:2021-11-03 11:07:57
【问题描述】:

使用(使用 vuex 操作)获取数据、获取数据并将第一项设置为选定选项的正确方法是什么?

我现在得到的是一个带有角色选择框的AddUser 表单。在创建的函数中,我使用 vuex 调用 fetchRoles 函数从后端获取可用角色。我创建了一个计算属性 roles 以从商店中取回角色。最后,我想要一个本地 selectedRole 变量,默认为第一个角色。

<script>
    export default {
        created() {
            this.$store.dispatch('roles/fetchRoles');
        },
        computed: {
            roles() {
                return this.$store.getters['roles/roles'];
            },
        },
        data() {
            return {
                selectedRole: this.roles[0],
            };
        },
    };
</script>

因为在计算的this.roles[0] 未定义之前数据正在运行。我可以将代码更改为this.roles.length &gt; 0 ? this.roles[0] : null,但当角色最终可用时,变量不会更新。一个可能的解决方案是使用 watch 属性,但我觉得这个概念必须有更好的方法。

额外代码

fetchRoles 操作

export async function fetchRoles(context) {
    try {
        if (context.state.roles.length === 0) {
            const response = await axios.get('roles');
            const roles = response.data.roles;
            return await context.commit('setRoles', roles);
        }
    } catch (error) {
        console.log(error);
        return error;
    }
}

setRoles 突变

export function setRoles(state, roles) {
    state.roles = roles;
}

角色获取者

export function roles(state) {
    return state.roles;
}

【问题讨论】:

    标签: vue.js axios vuex


    【解决方案1】:

    您可以等待fetchRoles 操作并在之后分配您的变量;

    async created() {
        await this.$store.dispatch('roles/fetchRoles');
        this.selectedRole = this.roles[0];
    }
    

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    const store = new Vuex.Store({
      state: {
        posts: null
      },
      actions: {
        async fetchPosts() {
    const posts = await fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json());
      this.commit('setPosts', posts)
        }
      },
      mutations: {
        setPosts(state, posts) {
          state.posts = posts;
        }
      }
    })
    
    
    
    var app = new Vue({
      el: '#app',
      store,
      data: {
        firstPost: null
      },
      computed: {
        posts() {
          return this.$store.state.posts;
        }
      },
      async created() {
        await this.$store.dispatch('fetchPosts');
        this.firstPost = this.posts[0];
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
    
    <div id="app">
      <div v-if="firstPost">
        firstPost : {{ firstPost.title }}
      </div>
      <div v-else>
        Loading...
      </div>
    </div>

    【讨论】:

    • 工作!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多