【问题标题】:VueJS/VueX : display table when store state has been populatedVueJS/VueX:当存储状态被填充时显示表格
【发布时间】:2019-08-17 02:23:18
【问题描述】:

我正在尝试开发一个单一的文件组件,我想从后端获取用户汽车并在表格中显示所有加载的汽车。

最好的处理方法是什么?

目前,我从 created() 钩子调用 store 操作 (getUserCars),然后我尝试使用 watch 监听我的 store 的 state 属性的任何更改能够在 UI 中构建我的表格。但它还没有工作..

你能帮帮我吗?

<script>
import { mapActions, mapGetters } from "vuex";

export default {
    created: function() {
        console.log("created() - called");
        this.getUserCars();
    },
    mounted: function() {
        console.log("mounted() - called");
    },
    destroyed: function() {
        console.log("destroyed() - called");
    },
    watch: {
        userSites(newValue, oldValue) {
            console.log(`watch() Updating from ${oldValue} to ${newValue}`);

            const options = {
                data: {type: "local", source: this.userCars(), pageSize: 5},
                layout: {theme: "default", class: "", scroll: !1, footer: !1},
                sortable: !0,
                pagination: !0,
                columns: [
                    {field: "name", title: "Name"},
                    {field: "createdAt", title: "Created At"}
                ]
            };
            $('#m_datatable').mDatatable(options);

        },
    },
    computed: {

    },
    methods: {
        ...mapGetters(["userCars"]),
        ...mapActions(["getUserCars"]),
    }
};
</script>

【问题讨论】:

  • 我认为你不需要手表。您是否尝试过使用计算属性?
  • 默认情况下,存储状态也是反应式的。如果状态发生变化,它将更新 UI。但动作必须在计算属性内。
  • @varit05 好的,那么我需要将负责构建数据表的代码放在哪里?
  • 您的 UI 是否直接与数据库交互,没有任何 REST Api/Service?
  • 不,首先我使用 REST API 调用获取汽车列表,并使用状态属性中的突变存储它们。然后,我想自动获取刚刚加载的汽车列表,以使用我在描述中添加的 javascript 代码创建我的数据表

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

如果您在商店中的 getUserCars() 操作使用数据来补充状态,那么您可以拥有像 userCars 这样的 getter,我可以在您的代码中看到它。 您只需将 mapGetters 助手从方法移至计算。

然后你可以在模板中访问它并做任何你想做的事情。

computed: {
    ...mapGetters(["userCars"])
},
methods: {
    ...mapActions(["getUserCars"])
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2019-11-10
    • 1970-01-01
    • 2020-07-03
    • 2017-10-30
    • 2021-07-16
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多