Home Web Front-end JS Tutorial Summary of data transfer methods for Vue form class parent-child components

Summary of data transfer methods for Vue form class parent-child components

May 14, 2018 am 11:57 AM
transfer data components

This time I will bring you a summary of the data transfer methods of the Vue form class parent-child component. What are the precautions for the data transfer of the Vue form class parent-child component. The following is a practical case, let's take a look.

If you use Vue.js for project development, you will inevitably use a component-based development method. This method does bring certain convenience to development and maintenance, but if it involves data and data between components, State transfer interaction is a troublesome thing, especially when facing a page with a lot of forms.

Here I will record my usual processing methods. This article mainly records the data transfer between parent and child components. Non-parent and child components are mainly processed through Vuex. This article will not explain it for the time being.

Same as the solution given in the document, the parent component transmits data to the child component mainly through props, and the child component transmits data to the parent component mainly through trigger $emit(), just in usage It will be a little different.

1. Pass basic type data

#When the sub-component has less content, basic type data will be passed directly, usually String, Number , Boolean three types.

Let’s look at an example first:

<!-- 父组件 parent.vue -->
<template>
  <p class="parent">
    <h3>问卷调查</h3>
    <child v-model="form.name"></child>
    <p class="">
      <p>姓名:{{form.name}}</p>
    </p>
  </p>
</template>
<script>
  import child from './child.vue'
  export default {
    components: {
      child
    },
    data () {
      return {
        form: {
          name: '请输入姓名'
        }
      }
    }
  }
</script>
Copy after login
<!-- 子组件 child.vue -->
<template>
  <p class="child">
    <label>
      姓名:<input type="text" :value="currentValue" @input="changeName">
    </label>
  </p>
</template>
<script>
  export default {
    props: {
      // 这个 prop 属性必须是 valule,因为 v-model 展开所 v-bind 的就是 value
      value: ''
    },
    methods: {
      changeName (e) {
        // 给input元素的 input 事件绑定一个方法 changeName 
        // 每次执行这个方法的时候都会触发自定义事件 input,并且把输入框的值传递进去。
        this.$emit('input', e.target.value)
      }
    }
  }
</script>
Copy after login

Bind a method changeName to the input event of the subcomponent. Each time this method is executed, the custom event input will be triggered and the value of the input box will be changed. Pass it in.

The parent component binds a value through the v-model directive to receive the data passed by the child component. But this only responds to the data of the child component from the parent component. If you want the child component to respond to the data passed by the parent component, you need to define a props attribute value for the child component, and this attribute must be value and cannot be written with other words.

v-model is actually a syntactic sugar. For details, please refer to the form input component using custom events.

2. Pass reference type data

When there is a lot of content in the sub-component, for example, the sub-component has multiple form elements, if there are still If you bind a value to each form element as above, you will need to write a lot of repeated code. So what is usually passed at this time is an object. The basic principle of value passing remains the same, but the writing method will be slightly different.

Let’s look at the code first:

<!-- 父组件 parent.vue -->
<template>
  <p class="parent">
    <h3>问卷调查</h3>
    <child :formData.sync="form"></child>
    <p class="">
      <p>姓名:{{form.name}}</p>
    </p>
  </p>
</template>
<script>
  import child from './child.vue'
  export default {
    components: {
      child
    },
    data () {
      return {
        form: {
          name: '请输入姓名',
          age: '21'
        }
      }
    }
  }
</script>
Copy after login
<!-- 子组件 child.vue -->
<template>
  <p class="child">
    <label>
      姓名:<input type="text" v-model="form.name">
    </label>
    <label>
      年龄:<input type="text" v-model="form.age">
    </label>
    <label>
      地点:<input type="text" v-model="form.address">
    </label>
  </p>
</template>
<script>
  export default {
    data () {
      return {
        form: {
          name: '',
          age: '',
          address: ''
        }
      }
    },
    props: {
      // 这个 prop 属性接收父组件传递进来的值
      formData: Object
    },
    watch: {
      // 因为不能直接修改 props 里的属性,所以不能直接把 formData 通过v-model进行绑定
      // 在这里我们需要监听 formData,当它发生变化时,立即将值赋给 data 里的 form
      formData: {
        immediate: true,
        handler (val) {
          this.form = val
        }
      }
    },
    mounted () {
      // props 是单向数据流,通过触发 update 事件绑定 formData,
      // 将 data 里的 form 指向父组件通过 formData 绑定的那个对象
      // 父组件在绑定 formData 的时候,需要加上 .sync
      this.$emit('update:formData', this.form)
    }
  }
</script>
Copy after login

props is a one-way data flow. When we need to bidirectionally bind the properties in props, we need to use the .sync modifier. Please check for details. Refer to the .sync modifier, which will not be described here.

It should be noted here that props cannot be modified directly in vue, so if we want to pass values ​​to the parent component, we still need to modify the values ​​in data. Props only exist as the middleman for the call between father and son. .

In addition, if we want to preview the data initially passed by the parent component, we need to monitor the prop changes through watch and pass the value in when the child component is initialized.

Note: I put this.$emit('update:formData', this.form) in mounted in the subcomponent. The reason is to avoid loading each input The custom event is triggered in the input event of the tag, but the premise of writing this is that the parent and child components must share the same object.

This is what the above code says. When using: formData.sync="form" to bind a value in the parent component, form is an object, and the custom event in the child component is triggered this.$emit(' update:formData', this.form) , this.form must also be an object.

It should also be noted here that if multiple sub-components use an object, then this writing method should be avoided, because if one component modifies the data of this object, other sub-components will also change accordingly. .

So when I use it, I allocate an object of its own to each sub-component, for example:

data () {
 return {
  parentObject: {
   child_1_obj: {},
   child_2_obj: {},
  }
 }
}
Copy after login

This is the data defined in the parent component. Of course, the name will not be chosen like this. .

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of vue components

Detailed explanation of the use of vue cropping preview component

The above is the detailed content of Summary of data transfer methods for Vue form class parent-child components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

How to use Excel filter function with multiple conditions How to use Excel filter function with multiple conditions Feb 26, 2024 am 10:19 AM

If you need to know how to use filtering with multiple criteria in Excel, the following tutorial will guide you through the steps to ensure you can filter and sort your data effectively. Excel's filtering function is very powerful and can help you extract the information you need from large amounts of data. This function can filter data according to the conditions you set and display only the parts that meet the conditions, making data management more efficient. By using the filter function, you can quickly find target data, saving time in finding and organizing data. This function can not only be applied to simple data lists, but can also be filtered based on multiple conditions to help you locate the information you need more accurately. Overall, Excel’s filtering function is a very practical

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training Mar 11, 2024 pm 12:10 PM

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects

See all articles