search
HomeWeb Front-endJS TutorialHow to operate vue components and use props to pass data

This time I will show you how to use props to transfer data when operating a vue component. What are the precautions for using props to transfer data when operating a vue component? The following is a practical case, let’s take a look.

In Vue, the relationship between parent and child components can be summarized as props are passed downwards and events are passed upwards. The parent component sends data to the child component through props, and the child component sends messages

to the parent componentthrough events. See how they work.

1. Basic Usage

Components are not just about reusing the content of the template. What's more important is communication between components.

In the component, use the option props to declare the data that needs to be received from the parent. The value of props can be two types, one is a

stringarray, and the other is an object.

1.1 String array:

  <p>
   <my-component4></my-component4>
  </p>
Vue.component('my-component4',{
 props: ['message'],
 template: '<p>{{message}}</p>'
});
var app4 = new Vue({
 el: '#app4'
});
The result after rendering is: The data declared in

<p>
  </p><p>
</p>
props and the data returned by the component data function are mainly The difference is that the props come from the parent, while the data in the data is the component's own data, and the scope is the component itself. Both of these data can be used in the template template and calculated properties computed and

methods.

The data message in the above example is passed from the parent through props. Write the name of the props directly on the custom label of the component. If you want to pass multiple data, just add items in the props array. .

Sometimes, the data passed is not directly hard-coded, but dynamic data from the parent. In this case, you can use the command v -bind to dynamically bind the value of props. When the data of the parent component changes , will also be passed to child components.

  <p>
   <input>
   <my-component5></my-component5>
  </p>
Vue.component('my-component5',{
 props: ['myText'],
 template: '<p>{{myText}}</p>'
});
var app5 = new Vue({
 el: '#app5',
 data: {
  text: '动态传递父组件数据'
 }
});
A few points to note:

1. If you want to directly pass numbers, Boolean values, arrays, and objects, and do not use v-bind, only strings will be passed.

2. If you want to pass all the properties of an object as props, you can use v-bind without any parameters (that is, use v-bind instead of v -bind:prop-name). For example, a known todo object:

1.2 Object:

When prop needs to be verified, object writing is required.

Generally when your component needs to be provided to others, it is recommended to perform data verification. For example, a certain data must be of numeric type. If a string is passed in, a warning will pop up on the console.

 <p>
   <input>
   <my-component6></my-component6>
  </p>
Vue.component('my-component6',{
 props: {
  'myText':{
   type: Number, //必须是数字类型的
   required: true, //必须传值
   default: 1 //如果未定义,默认值就是1
  }
 },
 template: '<p>{{myText}}</p>'
});
var app6 = new Vue({
 el: '#app6',
 data: {
  number: 1
 }
});
The verified type type can be:

• String

• Number
• Boolean
• Object
• Array
• Function

type can also be a custom constructor, detected using instanceof.

When prop verification fails, a warning will be thrown in the console under the development version.

2. One-way data flow

The biggest change between Vue 2.x and Vue l.x is that Vue2.x is passed through props The data is one-way, that is, when the data of the parent component changes, it will be passed to the child component, but not the other way around.

In business, we often encounter two situations where prop needs to be changed.

2.1 One is that the parent component passes in the initial value, and the subcomponent saves it as the initial value. It can be used and modified at will within the scope. (After Prop is passed in as the initial value, the subcomponent wants to use it as local data;)

In this case, you can declare another data in the component data and reference the prop of the parent component. The sample code is as follows :

 <p>
   <my-component7></my-component7>
  </p>
Vue.component('my-component7',{
 props: ['initCount'],
 template: '<p>{{count}}</p>',
 data: function(){
  return {
   count: this.initCount
  }
 }
});
var app7 = new Vue({
 el: '#app7'
});
The data count is declared in the component. It will obtain the initCount from the parent component when the component is initialized. After that, it has nothing to do with it. It only maintains the count, so that you can avoid directly operating the initCount.

2.2 Prop is passed in as the original value that needs to be transformed. (Prop is passed in as raw data, and is processed by the subcomponent into other data output.)

In this case, calculated properties are enough. The sample code is as follows:

  <p>
   <my-component8></my-component8>
  </p>
Vue.component('my-component8',{
 props: ['width'],
 template: '<p>组件内容</p>',
 computed: {
  style: function(){
   return {
    width: this.width+'px'
   }
  }
 }
});
var app8 = new Vue({
 el: '#app8'
});

注意在 JavaScript 中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎么实现微信小程序登录鉴权

使用webpack插件html-webpack-plugin实例详解

The above is the detailed content of How to operate vue components and use props to pass data. 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
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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment