vue2.x study notes (fourteen)

Then the previous content: https://www.cnblogs.com/yanggb/p/12602256.html .

Prop of components

Prop is an important way of communication between components, it is very important to understand their knowledge.

Prop case (camelCase vs kebab-case)

We know that the attribute names in html are not case sensitive, because the browser will interpret all uppercase characters as lowercase characters. This means that when you use a template in dom, the prop name of camelCase (camel-case nomenclature) needs to be named using its equivalent kebab-case (nocturnal line separation nomenclature).

Vue.component ('blog-post' , {
   // 
  CamelCase props in JavaScript : ['postTitle' ], 
  template: '<h3> {{postTitle}} </ h3>' 
})
<!- Kebab-case in HTML- > 
< blog-post post-title = "hello!" > </ Blog-post >

Again, if you use a string template, this limitation does not exist.

Types of Prop

In all the previous content, we have only seen the props listed as a string array.

props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

But in many cases, we will hope that each prop has a specified value type. Therefore, vue supports listing props in the form of objects. The names and values ​​of these properties are the respective names and types of props:

props: {
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise // or any other constructor
}

This way not only provides documentation for your components, but also prompts the user from the browser's javascript console when they encounter the wrong type.

Pass static or dynamic Prop

Like this, you already know that you can pass a static value to prop like this:

<blog-post title="My journey with Vue"></blog-post>

You also know that prop can be dynamically assigned through the [v-bind] command:

<!- Dynamically assign a variable value- > 
< blog-post v-bind: title = "post.title" > </ blog-post > 

<!- Dynamically assign a complex expression value- > 
< blog-post
   v-bind: title = "post.title + 'by' + post.author.name" 
> </ blog-post >

In the above two examples, the values ​​we pass in are all of type string. In fact, any type of value can be passed to a prop.

Pass in a number to prop

<!- Even if 42 is static, we still need v-bind to tell Vue that this is a JavaScript expression instead of a string, otherwise it will be treated as a string. -> 
< blog-post v-bind: likes = "42" > </ blog-post > 

<!- Use a variable for dynamic assignment. -> 
< blog-post v-bind: likes = "post.likes" > </ blog-post >

Pass a boolean value to prop

<!- Including the case where the prop has no value, it means true, which is a special syntax for boolean props. -> 
< blog-post is-published > </ blog-post > 

<!- Even if false is static, we still need v-bind to tell Vue that this is a JavaScript expression instead of a string, otherwise it will Treated as a string. -> 
< blog-post v-bind: is-published = "false" > </ blog-post > 

<!- Use a variable for dynamic assignment. -> 
< blog-post v-bind: is-published = "post.isPublished" > </ blog-post >

Pass in an array to prop

<!- Even if the array is static, we still need v-bind to tell Vue that this is a JavaScript expression instead of a string, otherwise it will be treated as a string. -> 
< blog-post v-bind: comment-ids = "[234, 266, 273]" > </ blog-post > 

<!- Use a variable for dynamic assignment. -> 
< blog-post v-bind: comment-ids = "post.commentIds" > </ blog-post >

Pass an object to prop

<!- Even if the object is static, we still need v-bind to tell Vue that this is a JavaScript expression instead of a string, otherwise it will be treated as a string. -> 
< blog-post
   v-bind: author = "{ 
    name: 'Veronica', 
    company: 'Veridian Dynamics' 
  }" > </ blog-post > 

<!- Use a variable for dynamic assignment. -> 
< blog-post v-bind: author = "post.author" > </ blog-post >

Pass all properties of an object to prop

If you want to pass in all the properties of an object as prop, you can use the [v-bind] command without parameters (instead of the [v-bind: prop-name] command).

For example, for a given object post:

post: {
  id: 1,
  title: 'My Journey with Vue'
}

The following template:

<blog-post v-bind="post"></blog-post>

Equivalent to:

<blog-post
  v-bind:id="post.id"
  v-bind:title="post.title"></blog-post>

Note the distinction from passing an object above, the difference is that the receiver defines props.

Unidirectional data flow

All props form a one-way downward binding between the parent and child props: the update of the parent prop will flow down into the child components, but the reverse is not possible. The purpose of this design is to prevent the accidental change of the state of the parent component from the child component, thus causing the data flow of your application to become difficult to understand.

In addition, every time the parent component is updated, all props in the child component will be refreshed to the latest value. This means that you should not change the prop inside a sub-component, otherwise vue will issue a warning in the browser console, because this is a behavior that will make your data flow logic become confusing.

There are two common cases of trying to change a prop:

1. A prop was originally designed to be used to pass an initial value, but the sub-components then want to use it as a local prop data. In this case, it is best to define a local hit attribute and use this prop as its initial value.

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

2. A prop is designed to be converted after the original value is passed in. In this case, it is best to use the value of this prop to define a calculated property.

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

It should be noted that in JavaScript, objects and arrays are passed in by reference, so for an array or object type prop, changing this object or array itself in a child component will affect the state of the parent component.

prop verification

We can also specify verification requirements for the component's prop. If a requirement is not met, vue will warn you in the browser console. Such a mechanism is especially helpful when developing a component that will be used by others.

In order to customize the verification method of props, you can provide an object with verification requirements for the values ​​in props instead of a string array.

Vue.component ('my-component' , { 
  props: { 
    // basic type checking (null and undefined will pass any type verification) 
    propA: Number,
     // multiple possible types 
    propB: [String, Number],
     / / Required string 
    propC: { 
      type: String, 
      required: true 
    }, 
    // 
      Number with default value 
    propD: { type: Number, 
      default : 100 
    }, 
    // Object with default value 
    propE: { 
      type : Object, 
      // The default value of the object or array must be obtained from a factory function 
      default : function () {
         return {message: 'hello'} 
      } 
    }, 
    // Custom validation function 
    propF: { 
      validator: function (value) {
         // This value must match one of the following strings 
        return ['success', 'warning', 'danger']. IndexOf (value )! == -1 
      } 
    } 
  } 
})

When the prop verification fails, the development environment build version of vue will generate a console warning.

In addition, it should be noted that prop will be verified before a component instance is created, so the properties of the instance (such as data, computed, etc.) are not available in the default or validator function. Therefore, please do not use the attributes of the instance in the default or validator functions, otherwise the verification may fail all the time.

Type check

The type type can be one of the following native constructors (note the strict case sensitivity):

String
Number
Boolean
Array
Object
Date
Function
Symbol

In addition, type can also be a custom constructor.

function Person (firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}
Vue.component('blog-post', {
  props: {
    author: Person
  }
})

In fact, the type check is checked by the instanceof keyword, so in the above example, the verification method is to verify whether the value of the author attribute is created by new Person.

Non-prop attribute

A non-prop attribute refers to a component, but the component does not have an attribute defined by the corresponding prop.

Because explicitly defined props are suitable for passing information to a subcomponent, the author of the component library cannot always foresee what scenarios the component will be used for. This is why components can receive arbitrary attributes, and these attributes will be added to the root element of this component.

For example, imagine that you reference a third-party <bootstrap-date-input> component through a bootstrap plugin. This plugin needs to use a data-date-picker attribute on its <input>. We can pass this attribute Add to the component instance, so that this attribute is automatically added to the root element <input> of the <bootstrap-date-input> component, and the parameter is passed to the third-party plug-in through the component.

<bootstrap-date-input data-date-picker="activated"></bootstrap-date-input>

This mechanism will come in handy in such special scenarios.

Replace / Merge existing attributes

Imagine the template for <bootstrap-date-input> like this:

<input type="date" class="form-control">

In order to customize a theme for our date picker plugin, we may need to add a special class name like this:

<bootstrap-date-input
  data-date-picker="activated"
  class="date-picker-theme-dark"></bootstrap-date-input>

In this case, we have defined two different class values:

1.form-control: This is set in the template of the component.

2.date-picker-theme-dark: This is passed in from the parent of the component.

For most attributes, the value provided to the component from the outside will replace the value set inside the component. Therefore, if type = "text" is passed in, it will be replaced with type = "date" and destroyed! The class and style attributes are slightly smarter, not [replacement], but [merging], so the final value obtained in the above example is form-control data date-picker-theme-dark, the externally imported class The value will be added after the internally defined class value.

Disable attribute inheritance

If you don't want the root element of the component to inherit the attribute, you can do this by setting [inheritAttrs: false] in the component's options.

Vue.component('my-component', {
  inheritAttrs: false,
  // ...
})

This is especially suitable for use with the $ attrs attribute of an instance, which contains the attribute name and attribute value passed to a component, for example:

{
  required: true,
  placeholder: 'Enter your username'
}

With [inheritAttrs: false] and [$ attrs], you can manually decide which element these attributes will be assigned to, which is often used when writing basic components.

Vue.component('base-input', {
  inheritAttrs: false,
  props: ['label', 'value'],
  template: `
    <label>
      {{ label }}
      <input
        v-bind="$attrs"
        v-bind:value="value"
        v-on:input="$emit('input', $event.target.value)">
    </label>
  `
})

This pattern allows you to use the original html element when using the basic component, without worrying about which element is the real root element.

<base-input
  v-model="username"
  required
  placeholder="Enter your username"></base-input>

In the above example, although the [inheritAttrs: false] option is used in the component to prevent the root element in the component from automatically inheriting the attributes passed from the parent component, but because <v-bind = "$ attrs is added to <input> "] Instruction (the role of $ attrs is to get all the attributes passed from the parent component), which is equivalent to inheriting all the attributes passed from the parent component. In addition, regardless of whether the [inheritAttrs: false] attribute is used, you can use the global attribute [$ attrs] provided by vue to obtain the attributes passed from the parent component.

The last thing to note is that because of the particularity of the two attributes of style and class, the [inheritAttrs: false] option does not affect the binding of style and class, they will still be inherited and merged by the root element in the component.

 

"I still like you very much, like leaving white in ink and blue, without leaving any traces."

Guess you like

Origin www.cnblogs.com/yanggb/p/12609450.html