如何将数据属性设置为从Vuex getter返回的值

Lin*_*inx 3 data-binding vue.js vuex

我有一个Vue组件,它将根据用户之前在前一个组件中单击的内容显示数据.当他们最初点击时,我设置'当前'索引.然后,当他们到达下一页时,我有一个将在数据数组中查找并返回"当前"数据的getter.

他们被重定向到的组件是他们可以编辑的表单.我希望能够预先填充"当前"数据.不作为占位符,而是作为实际值,以便他们可以直接编辑它.

问题是我不知道如何将从getter返回的值设置为数据函数值,以便它们可以与v-model绑定.

HTML

<input type="text" class="form-control" id="nickname1" v-model="name" name="name">
<input type="text" class="form-control" id="address1" placeholder="" v-model="address" name="address" > 
<input type="text" class="form-control" id="city1" placeholder="" v-model="city" name="city" > 
Run Code Online (Sandbox Code Playgroud)

VUE

data: function() {
    return {
        name: this.currentArea.title,
        address: this.currentArea.address,
        city: this.currentArea.city,
        state: this.currentArea.state
    }
},
computed: {
    currentArea() { return this.$store.getters.currentArea }
}
Run Code Online (Sandbox Code Playgroud)

*this.currentArea.title和currentArea.title不起作用.

*如果我绑定占位符,数据显示正确,因此getter函数正确返回currentArea

tha*_*ksd 11

data方法仅在初始化期间,设置计算属性之前触发一次.因此,currentAreadata方法内部引用将不会像undefined执行时那样工作.

如果this.$store.getters.currentArea预计不会改变此组件的生命周期,那么在mounted钩子中设置一次数据属性是最简单的:

data() {
  return {
    name: '',
    address: '',
    city: '',
    state: ''
  }
},
mounted() {
  let area = this.$store.getters.currentArea;
  this.name = area.name;
  this.address = area.address;
  this.city = area.city;
  this.state = area.state;       
} 
Run Code Online (Sandbox Code Playgroud)

或者,如果您知道此组件的数据属性将始终与该组件的数据属性相同,则currentArea只需直接返回this.$store.getters.currentAreadata方法:

data() {
  return this.$store.getters.currentArea;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*zza 5

@thanksd:谢谢你的回答。我正在研究状态存储在 vuex 中的场景,暂时将不完整的内容发送到组件,然后通过 fetch 进行更新。它应该可以在表单中编辑。

我的解决方案是在 vuex 中使用 getter 导出部分状态:

getters: {
  getItemDetail: (state, getters) => (id) => {
    let item = state.openedItems.items.find(i => i.id === id);
    return item ? item.data : null;
  }
}
Run Code Online (Sandbox Code Playgroud)

通过组合数据、计算和监视属性(并在 lodash 的帮助下深度克隆对象)在组件中使用它:

data () {
  return {
    itemDetail: null
  };
},
computed: {
  itemData () {
    return this.$store.getters.getItemDetail(this.item.id);
  }
},
watch: {
  itemData (n, o) {
    this.itemDetail = _.cloneDeep(n);
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,我将输入绑定到“itemDetail”(在我的示例中使用元素开关):

<el-switch v-model="itemDetail.property"></el-switch>
Run Code Online (Sandbox Code Playgroud)

对我来说(但我对 Vue 很陌生),这似乎是一个很好的折衷方案。

  • 这已经让我想了一个星期,而你的答案终于有所帮助 - 非常感谢! (2认同)