search
HomeWeb Front-endJS TutorialSummary of data transfer methods for Vue form class parent-child 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>
    </p>
<h3 id="问卷调查">问卷调查</h3>
    <child></child>
    <p>
      </p>
<p>姓名:{{form.name}}</p>
    
  
</template>
<script>
  import child from &#39;./child.vue&#39;
  export default {
    components: {
      child
    },
    data () {
      return {
        form: {
          name: &#39;请输入姓名&#39;
        }
      }
    }
  }
</script>
<!-- 子组件 child.vue -->
<template>
  <p>
    <label>
      姓名:<input>
    </label>
  </p>
</template>
<script>
  export default {
    props: {
      // 这个 prop 属性必须是 valule,因为 v-model 展开所 v-bind 的就是 value
      value: &#39;&#39;
    },
    methods: {
      changeName (e) {
        // 给input元素的 input 事件绑定一个方法 changeName 
        // 每次执行这个方法的时候都会触发自定义事件 input,并且把输入框的值传递进去。
        this.$emit(&#39;input&#39;, e.target.value)
      }
    }
  }
</script>

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>
    </p>
<h3 id="问卷调查">问卷调查</h3>
    <child></child>
    <p>
      </p>
<p>姓名:{{form.name}}</p>
    
  
</template>
<script>
  import child from &#39;./child.vue&#39;
  export default {
    components: {
      child
    },
    data () {
      return {
        form: {
          name: &#39;请输入姓名&#39;,
          age: &#39;21&#39;
        }
      }
    }
  }
</script>
<!-- 子组件 child.vue -->
<template>
  <p>
    <label>
      姓名:<input>
    </label>
    <label>
      年龄:<input>
    </label>
    <label>
      地点:<input>
    </label>
  </p>
</template>
<script>
  export default {
    data () {
      return {
        form: {
          name: &#39;&#39;,
          age: &#39;&#39;,
          address: &#39;&#39;
        }
      }
    },
    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(&#39;update:formData&#39;, this.form)
    }
  }
</script>

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: {},
  }
 }
}

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
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!