【问题标题】:How to init a component with the value of a VueX store field?如何使用 VueX 存储字段的值初始化组件?
【发布时间】:2019-12-14 03:44:49
【问题描述】:

我将 VueX store 插入 Vue 应用程序。

我应该如何处理表单中字段的值。

当表单初始化时,它应该使用存储中的值,但它不应该尝试更新不可变状态的值。

在我使用v-model 之前,我有点迷茫。

我尝试过类似的方法:

    computed: mapState(["profile"])
    data() {
      return {
        firstname: '',
      };
    },
    created() {
      this.firstname = this.profile.firstname;
    }

但是每次我重新打开组件时,它都不会更新商店中的值。

This solution 也不是我想要的,因为我希望使用来自服务器的值而不是当前正在编辑的值来更新存储。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

    最初状态值为空,尝试观察它并根据该值更新您的数据对象属性:

    computed: mapState(["profile"]),
    watch:{
       profile(val) {
           this.firstname = val.firstname;
       }
      },
       mounted() {
           this.firstname = this.profile.firstname;
       },
    

    【讨论】:

    • 这个手表好像没有设置初始值。
    【解决方案2】:

    我就是这样做的:

    • 在组件挂载时,我将字段值设置为组件状态
    • 然后我将 v-model 插入状态并使用操作在提交时更新存储。
    <template>
        <div id="login" class="cModal">
            <div>
                <header>
                    <h2>Edit Profile</h2>
                </header>
                <div>
                    <form @submit="edit()">
                        <div class="input-group">
                            <label for="firstname">Firstname</label>
                            <input id="firstname" type="text" v-model="firstname"/>
                        </div>
                        <div class="input-group">
                            <button>Edit profile</button>
                        </div>
                    </form>
                </div>
                <footer class="cf">
                    <a href="#" class="btn" @click="closeModal">Fermer [x]</a>
                </footer>
            </div>
        </div>
    </template>
    
    <script>
      import { mapState } from 'vuex';
      export default {
        computed: mapState(["profile"]),
        data() {
          return {
            firstname: '',
          };
        },
        created() {
          this.firstname = this.profile.firstname;
        },
        methods: {
          edit() {
            this.$emit("handleProfileUpdate", {firstname: this.firstname});
          },
          closeModal() {
            this.$emit("close");
          },
        }
      };
    </script>
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 2021-09-16
      • 2020-06-02
      • 2019-12-21
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2020-06-21
      • 2016-11-20
      相关资源
      最近更新 更多