Vue component options props
Previous words
Most of the options accepted by the component are the same as the Vue instance, and the option props is a very important option in the component. In Vue, the relationship between parent and child components can be summarized as props down, events up. The parent component passes data down to the child component through props, and the child component sends messages to the parent component through events. This article will introduce in detail the Vue component option props
static props
The scope of the component instance is isolated. This means that you cannot (and should not) reference the parent component's data directly within the child component's template. To allow the child component to use the data of the parent component, you need to pass the props option of the child component
Using Prop to transfer data includes static and dynamic forms. The following will introduce the static props
The child component must be displayed Formulaly declare the data it expects to obtain using the props
option
var childNode = { template: '<p>{{message}}</p>', props:['message'] }
Static Prop passes as a placeholder for the child component in the parent component Add attributes to achieve the purpose of passing values
<p id="example"> <parent></parent></p>
<script>var childNode = { template: '<p>{{message}}</p>', props:['message'] }var parentNode = { template: ` <p class="parent"> <child message="aaa"></child> <child message="bbb"></child> </p>`, components: { 'child': childNode } };// 创建根实例new Vue({ el: '#example', components: { 'parent': parentNode } })</script>
Naming convention
For attributes declared by props, in the parent HTML template, the attribute name needs to be written with a dash
var parentNode = { template: ` <p class="parent"> <child my-message="aaa"></child> <child my-message="bbb"></child> </p>`, components: { 'child': childNode } };
When declaring child props attributes, you can use either camel case or underscore; when the child template uses variables passed from the parent, you need to use the corresponding camel case
var childNode = { template: '<p>{{myMessage}}</p>', props:['myMessage'] }
var childNode = { template: '<p>{{myMessage}}</p>', props:['my-message'] }
Dynamic props
In the template, you need to dynamically bind Setting the parent component's data to the child template's props is similar to binding to any ordinary HTML feature, using v-bind
. Whenever the data of the parent component changes, the change will also be transmitted to the child component
var childNode = { template: '<p>{{myMessage}}</p>', props:['myMessage'] }
##
var parentNode = { template: ` <p class="parent"> <child :my-message="data1"></child> <child :my-message="data2"></child> </p>`, components: { 'child': childNode }, data(){ return { 'data1':'aaa', 'data2':'bbb' } } };
<!-- 传递了一个字符串 "1" --><comp some-prop="1"></comp>
<p id="example"> <my-parent></my-parent></p>
<script>var childNode = { template: '<p>{{myMessage}}的类型是{{type}}</p>', props:['myMessage'], computed:{ type(){ return typeof this.myMessage } } }var parentNode = { template: ` <p class="parent"> <my-child my-message="1"></my-child> </p>`, components: { 'myChild': childNode } };// 创建根实例new Vue({ el: '#example', components: { 'MyParent': parentNode } })</script>
Because it is a literal prop, its value is the string
instead of number. If you want to pass an actual number, you need to use v-bind
so that its value is evaluated as a JS expression
<!-- 传递实际的 number --><comp v-bind:some-prop="1"></comp>
var parentNode = { template: ` <p class="parent"> <my-child :my-message="1"></my-child> </p>`, components: { 'myChild': childNode } };
Or you can use dynamic props and set the corresponding number 1
var parentNode = { template: ` <p class="parent"> <my-child :my-message="data"></my-child> </p>`, components: { 'myChild': childNode }, data(){ return { 'data': 1 } } };
Vue.component('example', { props: { // 基础类型检测 (`null` 意思是任何类型都可以) propA: Number, // 多种类型 propB: [String, Number], // 必传且是字符串 propC: { type: String, required: true }, // 数字,有默认值 propD: { type: Number, default: 100 }, // 数组/对象的默认值应当由一个工厂函数返回 propE: { type: Object, default: function () { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator: function (value) { return value > 10 } } } })
type
can be the following native constructorString Number Boolean Function Object Array Symbol
type
can also be a custom constructor Function, detected usinginstanceof.
When prop validation fails, Vue will throw a warning (if you are using the development version). props will be verified
before the component instance is created
default or validator function, such as
data,
computed Instance attributes such as or
methods cannot be used yet
The following is a simple example. If the message passed into the subcomponent is not a number, a warning will be thrown
<p id="example"> <parent></parent> </p>
<script> var childNode = { template: '<p>{{message}}</p>', props:{ 'message':Number } } var parentNode = { template: ` <p class="parent"> <child :message="msg"></child> </p>`, components: { 'child': childNode }, data(){ return{ msg: '123' } } }; // 创建根实例 new Vue({ el: '#example', components: { 'parent': parentNode } }) </script>
# Modify the content of the subcomponent in the above code as follows. You can customize the verification function. When the function returns When false, a warning prompt
var childNode = { template: '<p>{{message}}</p>', props:{ 'message':{ validator: function (value) { return value > 10 } } } }
## is output.
#var parentNode = { template: ` <p class="parent"> <child :message="msg"></child> </p>`, components: { 'child': childNode }, data(){ return{ msg:1 } } };
One-way data flow
prop is one-way binding: when the parent component When the property changes, it will be propagated to the sub-component, but not the other way around. This is to prevent child components from accidentally modifying the state of the parent component - which would make the application's data flow difficult to understand
另外,每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着不应该在子组件内部改变 prop。如果这么做了,Vue 会在控制台给出警告
下面是一个典型例子
<p id="example"> <parent></parent> </p>
<script> var childNode = { template: ` <p class="child"> <p> <span>子组件数据</span> <input v-model="childMsg"> </p> <p>{{childMsg}}</p> </p> `, props:['childMsg'] } var parentNode = { template: ` <p class="parent"> <p> <span>父组件数据</span> <input v-model="msg"> </p> <p>{{msg}}</p> <child :child-msg="msg"></child> </p> `, components: { 'child': childNode }, data(){ return { 'msg':'match' } } }; // 创建根实例 new Vue({ el: '#example', components: { 'parent': parentNode } }) </script>
父组件数据变化时,子组件数据会相应变化;而子组件数据变化时,父组件数据不变,并在控制台显示警告
修改子组件数据时,打开浏览器控制台会出现下图所示警告提示
修改prop数据
修改prop中的数据,通常有以下两种原因
1、prop 作为初始值传入后,子组件想把它当作局部数据来用
2、prop 作为初始值传入,由子组件处理成其它数据输出
[注意]JS中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态
对于这两种情况,正确的应对方式是
1、定义一个局部变量,并用 prop 的值初始化它
props: ['initialCounter'], data: function () { return { counter: this.initialCounter } }
但是,定义的局部变量counter只能接受initialCounter的初始值,当父组件要传递的值发生变化时,counter无法接收到最新值
<p id="example"> <parent></parent></p><script>var childNode = { template: ` <p class="child"> <p> <span>子组件数据</span> <input v-model="temp"> </p> <p>{{temp}}</p> </p> `, props:['childMsg'], data(){ return{ temp:this.childMsg } }, };var parentNode = { template: ` <p class="parent"> <p> <span>父组件数据</span> <input v-model="msg"> </p> <p>{{msg}}</p> <child :child-msg="msg"></child> </p> `, components: { 'child': childNode }, data(){ return { 'msg':'match' } } };// 创建根实例new Vue({ el: '#example', components: { 'parent': parentNode } })</script>
下面示例中,除初始值外,父组件的值无法更新到子组件中
2、定义一个计算属性,处理 prop 的值并返回
props: ['size'], computed: { normalizedSize: function () { return this.size.trim().toLowerCase() } }
但是,由于是计算属性,则只能显示值,而不能设置值
<script src="https://unpkg.com/vue"></script><script>var childNode = { template: ` <p class="child"> <p> <span>子组件数据</span> <input v-model="temp"> </p> <p>{{temp}}</p> </p> `, props:['childMsg'], computed:{ temp(){ return this.childMsg } }, };var parentNode = { template: ` <p class="parent"> <p> <span>父组件数据</span> <input v-model="msg"> </p> <p>{{msg}}</p> <child :child-msg="msg"></child> </p> `, components: { 'child': childNode }, data(){ return { 'msg':'match' } } };// 创建根实例new Vue({ el: '#example', components: { 'parent': parentNode } })</script>
下面示例中,由于子组件使用的是计算属性,所以,子组件的数据无法手动修改
3、更加妥帖的方案是,使用变量储存prop的初始值,并使用watch来观察prop的值的变化。发生变化时,更新变量的值
<p id="example"> <parent></parent></p><script>var childNode = { template: ` <p class="child"> <p> <span>子组件数据</span> <input v-model="temp"> </p> <p>{{temp}}</p> </p> `, props:['childMsg'], data(){ return{ temp:this.childMsg } }, watch:{ childMsg(){ this.temp = this.childMsg } } };var parentNode = { template: ` <p class="parent"> <p> <span>父组件数据</span> <input v-model="msg"> </p> <p>{{msg}}</p> <child :child-msg="msg"></child> </p> `, components: { 'child': childNode }, data(){ return { 'msg':'match' } } };// 创建根实例new Vue({ el: '#example', components: { 'parent': parentNode } })</script>
The above is the detailed content of Vue component options props. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



On the iPhone 15 Pro model, Apple has introduced three focal length options for shooting with the main camera. This article explains what these options are and how to set your preferred default focal length for taking photos. To take full advantage of the enhanced camera system on iPhone 15 Pro and iPhone 15 Pro Max, Apple has added three different focal length options to the main camera’s optical zoom. In addition to the standard default 1x (24mm) mode, Apple has added 1.2x (28mm) and 1.5x (35mm) settings. iPhone 15 Pro users can choose from these focal lengths when taking photos by simply tapping the 1x button in the Camera app. However, due to technical reasons, these focal
![Personal hotspot option not found on iPhone [Fixed]](https://img.php.cn/upload/article/000/887/227/168942511475372.png?x-oss-process=image/resize,m_fill,h_207,w_330)
When there is no Wi-Fi signal around us, what we think of is a personal hotspot on our iPhone, right? Recently, many iPhone users have commented that they cannot find the personal hotspot option on their iPhone and therefore, this creates a big problem for all of them. The main reasons that may cause this particular issue on your iPhone may include one of the following reasons. Small software bugs in iPhone. The iOS software on your iPhone is not updated to the latest version. Changes were made to the network settings on the iPhone. Do not update carrier settings (if any). There is a problem with the mobile network signal on the iPhone. After dealing with these factors we found an easy solution to this problem and used

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

Did you know that Apple outsources certain parts of its products to different countries? Yes. They are specifically intended for sale in these countries and are therefore manufactured there. You may have purchased a second-hand iPhone/iPad from someone else and may be wondering if it is possible to know which country your iPhone came from. Yes, there is a way to find out, and we will talk more about it now in this article. In this article, you will find an explanation of how to find out the country of origin of your iPhone using simple steps. How to Know the Country of Origin of iPhone Step 1: First, you should tap on the Settings icon from the home screen. Step 2: This is to open the Settings app, once opened, click on it to go to the General option as shown below.

The language bar is an important feature in Windows that allows users to quickly switch inputs instead of using the + keyboard shortcut. But in some cases, the dock option in the taskbar appears gray in Windows 11. This problem with WindowsSpacebar seems to be very common and there is no solution. We tried changing the language settings and reconfiguring the content, but to no avail. Although we finally managed to find the root cause and solution. Why can't I dock the language bar in the taskbar in Windows 11? You only have one language installed, and the language bar only works with multiple languages. The language is not installed correctly. A bug in Windows 11. Corrupted system files or user profiles. If in W

In iOS 17 and macOS Sonoma, Apple has added new formatting options for Apple Notes, including block quotes and a new Monostyle style. Here's how to use them. With additional formatting options in Apple Notes, you can now add block quotes to your notes. The block quote format makes it easy to visually offset sections of writing using the quote bar to the left of the text. Just tap/click the "Aa" format button and select the block quote option before typing or when you are on the line you want to convert to a block quote. This option applies to all text types, style options, and lists, including checklists. In the same Format menu you can find the new Single Style option. This is a revision of the previous "equal-width"

One of the most annoying changes that we users never want is the inclusion of "Show more options" in the right-click context menu. However, you can remove it and get back the classic context menu in Windows 11. No more multiple clicks and looking for these ZIP shortcuts in context menus. Follow this guide to return to a full-blown right-click context menu on Windows 11. Fix 1 – Manually adjust the CLSID This is the only manual method on our list. You will adjust specific keys or values in Registry Editor to resolve this issue. NOTE – Registry edits like this are very safe and will work without any issues. Therefore, you should create a registry backup before trying this on your system. Step 1 – Try it

How to handle checkboxes and radio buttons in PHP forms In web development, forms are one of the main ways of data interaction between applications and users. In forms, sometimes we need to use checkboxes and radiobuttons to select options. This article will explain how to handle checkboxes and radio buttons in PHP. 1. Checkbox processing In HTML, we can use <inputtype="checkbox&qu
