Table of Contents
Previous words
static props
Naming convention
Dynamic props
修改prop数据
Home Web Front-end JS Tutorial Vue component options props

Vue component options props

Aug 19, 2017 am 10:32 AM
props components Options

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']
}
Copy after login

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>
Copy after login

<script>var childNode = {
  template: '&lt;p&gt;{{message}}&lt;/p&gt;',
  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>
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: {
    'child': childNode
  }
};
Copy after login

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']
}
Copy after login
Copy after login

var childNode = {
  template: '<p>{{myMessage}}</p>',
  props:['my-message']
}
Copy after login

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']
}
Copy after login
Copy after login

##

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'
    }
  }
};
Copy after login

 

Passing numbers

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

<!-- 传递了一个字符串 "1" --><comp some-prop="1"></comp>
Copy after login

##
<p id="example">
  <my-parent></my-parent></p>
Copy after login

<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>
Copy after login

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 v-bind:some-prop="1"></comp>
Copy after login

var parentNode = {
  template: `  <p class="parent">
    <my-child :my-message="1"></my-child>
  </p>`,
  components: {
    'myChild': childNode
  }
};
Copy after login

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
    }
  }
};
Copy after login
## 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
      }
    }
  }
})
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, 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 id="example">
  <parent></parent>
</p>
Copy after login
Copy after login

<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>
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: '<p>{{message}}</p>',
  props:{
    'message':{
      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: {
    'child': childNode
  },
  data(){
    return{
      msg:1
    }
  }
};
Copy after login

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>
Copy after login
Copy after login

<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>
Copy after login

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

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

 

修改prop数据

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

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

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

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

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

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

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

  但是,定义的局部变量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>
Copy after login

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

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

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

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

<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>
Copy after login

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

  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>
Copy after login

 

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 set default camera focus on iPhone 15 Pro How to set default camera focus on iPhone 15 Pro Sep 22, 2023 pm 11:53 PM

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] Personal hotspot option not found on iPhone [Fixed] Jul 15, 2023 pm 08:45 PM

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

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

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

How to check iPhone model country How to check iPhone model country Jul 09, 2023 pm 11:33 PM

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.

Fix: Dock in taskbar option is grayed out on Windows 11 Fix: Dock in taskbar option is grayed out on Windows 11 Sep 15, 2023 pm 05:35 PM

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

How to use block quotes in Apple Notes How to use block quotes in Apple Notes Oct 12, 2023 pm 11:49 PM

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"

How to Default 'Show More Options' in Windows 11's Right-Click Menu How to Default 'Show More Options' in Windows 11's Right-Click Menu Jul 10, 2023 pm 12:33 PM

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 deal with checkboxes and radiobuttons in PHP forms How to deal with checkboxes and radiobuttons in PHP forms Aug 11, 2023 am 08:39 AM

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 &lt;inputtype="checkbox&qu

See all articles