如何正确地将数据从子组件传递到父组件和父组件到子组件?

2022-01-25 00:00:00 vue.js vue-component vuejs2

首先,这是我目前的结构

First of all, this is my current structure

子组件

// HTML
<v-select
 v-bind:items="selectItems"
 v-model="selectedItem"
 label="Category"
 item-value="text"
></v-select>
<v-text-field
 label="Enter Value"
 type="number"
 v-model="compVal"
></v-text-field>

// JS
props: {
 selectItems: {
  type: Array,
  required: true
 },
 selectedItem: {
  type: String
 },
 compVal: {
  type: Number
 },
}

父组件

// HTML

<component :selecItems="selectOneItems" :selectedItem="selectOneItem" 
:compVal="compOneVal"></component>

<component :selecItems="selectTwoItems" :selectedItem="selectTwoItem" 
:compVal="compTwoVal"></component>

// JS
data () {
 return {
  selectOneItems: [someArray],
  selectedOneItem: null,
  compOneVal: 0,
  selectTwoItems: [someArray],
  selectedTwoItem: null,
  compTwoVal: 0
 }
}

我的场景

1) 在初始状态,我必须从子文本输入中获取值并将其存储在本地.(孩子对父母)2)浏览器刷新后,我将检查任何本地数据,如果存在,我必须填充孩子的值(父母对孩子)

1) At initial state, i have to get value from Child's Text Input and store it in local. (Child to Parent) 2) After browser refresh, i will check for any local data, if it exsist, i have to populate child's value (Parent to Child)

当前结构的错误

每当我输入或选择某些内容时都会触发此错误

whenever i type or select something it triggers this error

避免直接修改 prop,因为每当父组件重新渲染时,该值都会被覆盖.相反,使用基于道具值的数据或计算属性.正在变异的道具:compOneValue"

那么如何避免这个错误呢?如何正确实现这个结构,以便我可以在任何我想要的地方重用这个组件.

so how to avoid this error? how to properly implement this structure, so that i can reuse this component wherever i want.

推荐答案

你正在使用 props 和 v-model.当父组件重新渲染时,道具将被覆盖.

You are using props with v-model. Props will be overridden when the parent component is re-renders.

使用 data 和 v-model 并从 props 中设置初始值:

Use data with v-model and set the initial values from the props:

子组件

// HTML
<v-select
  v-bind:items="selectItems"
  v-model="selectedItemModel"
  label="Category"
  item-value="text"
></v-select>
<v-text-field
  label="Enter Value"
  type="number"
  v-model="compValModel"
></v-text-field>

// JS
props: {
  selectItems: {
    type: Array,
    required: true
  },
  selectedItem: {
    type: String
  },
  compVal: {
    type: Number
  },
},

data: function() {
  return {
    selectedItemModel: this.selectedItem,
    compValModel: this.compVal
  }
}

可能值得将您的道具更改为 initialSelectedItem 和 initialCompVal,然后将数据属性称为 selectedItem 和 compVal.

It might be worth changing your props to be called initialSelectedItem and initialCompVal instead, and then have the data properties called selectedItem and compVal.

相关文章