Home > Web Front-end > JS Tutorial > Vue component options props

Vue component options props

大家讲道理
Release: 2017-08-19 10:32:07
Original
1824 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template