Home Web Front-end JS Tutorial Introduction to the use of Vue component option props

Introduction to the use of Vue component option props

Jun 29, 2018 pm 01:37 PM
props vue components

This article mainly introduces the use of Vue component option props. It has certain reference value. Now I share it with you. Friends in need can refer to it.

The parent component passes data downward through props. To the child component, the child component sends messages to the parent component through events. This article will introduce the Vue component option props in detail. Friends who need it can refer to the previous words

Most of the options accepted by the component are the same as those of the Vue instance The same, and 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 options props

static props

The scope of the component instance is isolated of. 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 use the props option of the child component

Using Prop to pass 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: &#39;<p>{{message}}</p>&#39;,
 props:[&#39;message&#39;]
}
Copy after login

Static Prop is achieved by adding attributes to the placeholder of the child component in the parent component. The purpose of passing the value

<script> var childNode = { template: &amp;#39;&lt;p&gt;{{message}}&lt;/p&gt;&amp;#39;, props:[&amp;#39;message&amp;#39;] } var parentNode = { template: ` <p class="parent"> <child message="aaa"></child> <child message="bbb"></child> </p>`, components: { &#39;child&#39;: childNode } }; // 创建根实例 new Vue({ el: &#39;#example&#39;, components: { &#39;parent&#39;: parentNode } }) </script>
Copy after login

##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: {
 &#39;child&#39;: childNode
 }
};
Copy after login

When declaring the child props attribute, 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: &#39;<p>{{myMessage}}</p>&#39;,
 props:[&#39;myMessage&#39;]
}
var childNode = {
 template: &#39;<p>{{myMessage}}</p>&#39;,
 props:[&#39;my-message&#39;]
}
Copy after login

Dynamic props

In the template, you need to dynamically bind the data of the parent component to the props of the child template, and bind Similar to any ordinary HTML feature, use v-bind. Whenever the data of the parent component changes, the change will also be transmitted to the child component

var childNode = {
 template: &#39;<p>{{myMessage}}</p>&#39;,
 props:[&#39;myMessage&#39;]
}
var parentNode = {
 template: `
 <p class="parent">
 <child :my-message="data1"></child>
 <child :my-message="data2"></child>
 </p>`,
 components: {
 &#39;child&#39;: childNode
 },
 data(){
 return {
 &#39;data1&#39;:&#39;aaa&#39;,
 &#39;data2&#39;:&#39;bbb&#39;
 }
 }
};
Copy after login

Pass the number

A common mistake beginners make is to use literal syntax to pass values

<!-- 传递了一个字符串 "1" -->
<comp some-prop="1"></comp>
<p id="example">
 <my-parent></my-parent>
</p>
<script>
var childNode = {
 template: &#39;<p>{{myMessage}}的类型是{{type}}</p>&#39;,
 props:[&#39;myMessage&#39;],
 computed:{
 type(){
 return typeof this.myMessage
 }
 }
}
var parentNode = {
 template: `
 <p class="parent">
 <my-child my-message="1"></my-child>
 </p>`,
 components: {
 &#39;myChild&#39;: childNode
 }
};
// 创建根实例
new Vue({
 el: &#39;#example&#39;,
 components: {
 &#39;MyParent&#39;: parentNode
 }
})
</script>
Copy after login

Because it is a literal prop whose value is the string "1" 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: {
 &#39;myChild&#39;: childNode
 }
};
Copy after login

Or you can use dynamic props and set the corresponding number 1 in the data attribute

var parentNode = {
 template: `
 <p class="parent">
 <my-child :my-message="data"></my-child>
 </p>`,
 components: {
 &#39;myChild&#39;: childNode
 },
 data(){
 return {
 &#39;data&#39;: 1
 }
 }
};
Copy after login

props verification

You can specify validation specifications for component props. Vue will issue a warning if the incoming data does not meet the specifications. This is useful when the component is used by others

To specify validation specifications, you need to use the form of an object, not a string array

Vue.component(&#39;example&#39;, {
 props: {
 // 基础类型检测 (`null` 意思是任何类型都可以)
 propA: Number,
 // 多种类型
 propB: [String, Number],
 // 必传且是字符串
 propC: {
 type: String,
 required: true
 },
 // 数字,有默认值
 propD: {
 type: Number,
 default: 100
 },
 // 数组/对象的默认值应当由一个工厂函数返回
 propE: {
 type: Object,
 default: function () {
 return { message: &#39;hello&#39; }
 }
 },
 // 自定义验证函数
 propF: {
 validator: function (value) {
 return value > 10
 }
 }
 }
})
Copy after login

Type can be the following native constructor

String
Number
Boolean
Function
Object
Array
Symbol
Copy after login

type can also be a custom constructor function, use instanceof to detect.

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, so in the default or validator function, instance properties such as data, computed or methods cannot be used yet

The following is a simple example, if the message of the sub-component is passed in If it is not a number, a warning will be thrown

<p id="example">
 <parent></parent>
</p>
<script>
var childNode = {
 template: &#39;<p>{{message}}</p>&#39;,
 props:{
 &#39;message&#39;:Number
 }
}
var parentNode = {
 template: `
 <p class="parent">
 <child :message="msg"></child>
 </p>`,
 components: {
 &#39;child&#39;: childNode
 },
 data(){
 return{
 msg: &#39;123&#39;
 }
 }
};
// 创建根实例
new Vue({
 el: &#39;#example&#39;,
 components: {
 &#39;parent&#39;: parentNode
 }
})
</script>
Copy after login

When the number 123 is passed in, there will be no warning. When the string '123' is passed in, the result is as follows

# 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: &#39;<p>{{message}}</p>&#39;,
 props:{
 &#39;message&#39;:{
 validator: function (value) {
 return value > 10
 }
 }
 }
}
Copy after login

is output. The msg value passed in the parent component is 1. Since it is less than 10, a warning prompt

## is output.

#
var parentNode = {
 template: `
 <p class="parent">
 <child :message="msg"></child>
 </p>`,
 components: {
 &#39;child&#39;: childNode
 },
 data(){
 return{
 msg:1
 }
 }
};
Copy after login

单向数据流

  prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解

  另外,每次父组件更新时,子组件的所有 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:[&#39;childMsg&#39;]
}
var parentNode = {
 template: `
 <p class="parent">
 <p>
 <span>父组件数据</span>
 <input v-model="msg">
 </p>
 <p>{{msg}}</p>
 <child :child-msg="msg"></child>
 </p>
 `,
 components: {
 &#39;child&#39;: childNode
 },
 data(){
 return {
 &#39;msg&#39;:&#39;match&#39;
 }
 }
};
// 创建根实例
new Vue({
 el: &#39;#example&#39;,
 components: {
 &#39;parent&#39;: parentNode
 }
})
</script>
Copy after login

  父组件数据变化时,子组件数据会相应变化;而子组件数据变化时,父组件数据不变,并在控制台显示警告

  修改prop中的数据,通常有以下两种原因

  1、prop 作为初始值传入后,子组件想把它当作局部数据来用

  2、prop 作为初始值传入,由子组件处理成其它数据输出

  对于这两种情况,正确的应对方式是

  1、定义一个局部变量,并用 prop 的值初始化它

props: [&#39;initialCounter&#39;],
data: function () {
 return { counter: this.initialCounter }
}
Copy after login

  2、定义一个计算属性,处理 prop 的值并返回

props: [&#39;size&#39;],
computed: {
 normalizedSize: function () {
 return this.size.trim().toLowerCase()
 }
}
Copy after login

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Vue.js通用应用框架-Nuxt.js的解析

关于vue.js简单配置axios的方法介绍

The above is the detailed content of Introduction to the use of Vue component option props. 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

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

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)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles