如何正确地将数据从子组件传递到父组件以及从父组件到子组件? [英] How to properly pass data from child to parent and parent to child component?

查看:27
本文介绍了如何正确地将数据从子组件传递到父组件以及从父组件到子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是我目前的结构

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.

推荐答案

您正在使用 propsv-model.当父组件重新渲染时,props 将被覆盖.

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

使用 datav-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
  }
}

可能值得将您的道具更改为 initialSelectedIteminitialCompVal,然后将数据属性称为 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.

这篇关于如何正确地将数据从子组件传递到父组件以及从父组件到子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆