search
HomeWeb Front-endJS TutorialVue component options props

Vue component options props

Aug 19, 2017 am 10:32 AM
propscomponentsOptions

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>
  <parent></parent></p>

<script>var childNode = {
  template: &#39;<p>{{message}}&#39;,
  props:[&#39;message&#39;]
}var parentNode = {
  template: `  <p class="parent">
    <child message="aaa">
    <child message="bbb">
  `,  components: {    &#39;child&#39;: childNode
  }
};// 创建根实例new Vue({
  el: &#39;#example&#39;,
  components: {    &#39;parent&#39;: 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>
    <child></child>
    <child></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>
    <child></child>
    <child></child>
  </p>`,
  components: {
    'child': childNode
  },
  data(){
    return {
      'data1':'aaa',
      'data2':'bbb'
    }
  }
};

 

Passing numbers

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

<!-- 传递了一个字符串 "1" --><comp></comp>

##
<p>
  <my-parent></my-parent></p>

<script>var childNode = {
  template: &#39;<p>{{myMessage}}的类型是{{type}}&#39;,
  props:[&#39;myMessage&#39;],
  computed:{
    type(){      return typeof this.myMessage
    }
  }
}var parentNode = {
  template: `  <p class="parent">
    <my-child my-message="1">
  `,  components: {    &#39;myChild&#39;: childNode
  }
};// 创建根实例new Vue({
  el: &#39;#example&#39;,
  components: {    &#39;MyParent&#39;: parentNode
  }
})</script>

Because it is a literal prop, its 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></comp>

var parentNode = {
  template: `  <p>
    <my-child></my-child>
  </p>`,
  components: {
    'myChild': childNode
  }
};

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

var parentNode = {
  template: `  <p>
    <my-child></my-child>
  </p>`,
  components: {
    'myChild': childNode
  },
  data(){
    return {
      'data': 1
    }
  }
};
## in the data attribute

#props verification

You can specify verification specifications for the props of the component. 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('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 constructor

String
Number
Boolean
Function
Object
Array
Symbol

type

can also be a custom constructor Function, detected using

instanceof. 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, 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>
  <parent></parent>
</p>

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

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: '<p>{{message}}</p>',
  props:{
    'message':{
      validator: function (value) {
        return value > 10
      }
    }
  }
}

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>
    <child></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>
  <parent></parent>
</p>

<script>
var childNode = {
  template: `
  <p class="child">
    <p>
      <span>子组件数据
      <input v-model="childMsg">
    
    <p>{{childMsg}}
  
  `,
  props:[&#39;childMsg&#39;]
}
var parentNode = {
  template: `
  <p class="parent">
    <p>
      <span>父组件数据
      <input v-model="msg">
    
    <p>{{msg}}
    <child :child-msg="msg">
  
  `,
  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>

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

  修改子组件数据时,打开浏览器控制台会出现下图所示警告提示

 

修改prop数据

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

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

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

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

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

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

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

  但是,定义的局部变量counter只能接受initialCounter的初始值,当父组件要传递的值发生变化时,counter无法接收到最新值

<p>
  <parent></parent></p><script></script><script>var childNode = {
  template: `  <p class="child">
    <p>
      <span>子组件数据
      <input v-model="temp">
    
    <p>{{temp}}
    `,
  props:[&#39;childMsg&#39;],
  data(){    return{
      temp:this.childMsg
    }
  },
};var parentNode = {
  template: `  <p class="parent">
    <p>
      <span>父组件数据
      <input v-model="msg">
    
    <p>{{msg}}
    <child :child-msg="msg">
    `,
  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>

  下面示例中,除初始值外,父组件的值无法更新到子组件中

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

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

  但是,由于是计算属性,则只能显示值,而不能设置值

<script></script><script>var childNode = {
  template: `  <p class="child">
    <p>
      <span>子组件数据
      <input v-model="temp">
    
    <p>{{temp}}
    `,
  props:[&#39;childMsg&#39;],
  computed:{
      temp(){        return this.childMsg
      }
  },
};var parentNode = {
  template: `  <p class="parent">
    <p>
      <span>父组件数据
      <input v-model="msg">
    
    <p>{{msg}}
    <child :child-msg="msg">
    `,
  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>

  下面示例中,由于子组件使用的是计算属性,所以,子组件的数据无法手动修改

  3、更加妥帖的方案是,使用变量储存prop的初始值,并使用watch来观察prop的值的变化。发生变化时,更新变量的值

<p>
  <parent></parent></p><script></script><script>var childNode = {
  template: `  <p class="child">
    <p>
      <span>子组件数据
      <input v-model="temp">
    
    <p>{{temp}}
    `,
  props:[&#39;childMsg&#39;],
  data(){    return{
      temp:this.childMsg
    }
  },
  watch:{
    childMsg(){      this.temp = this.childMsg
    }
  }
};var parentNode = {
  template: `  <p class="parent">
    <p>
      <span>父组件数据
      <input v-model="msg">
    
    <p>{{msg}}
    <child :child-msg="msg">
    `,
  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>

 

The above is the detailed content of Vue component options props. 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: 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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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

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),