And the use of personal understanding and Vue assembly introduction

The basic components used

Registration component

Registration component is the use of Vue.component () method to pass a custom component name, and then pass this configuration components.

 Vue.component ( 'mycomponent', {
  template: `<div> This is a custom component </ div>`,
  data () {
   return {
    message: 'hello world'
   }
  }
 })

The above manner, it has created a custom component, then it can be used in instances Vue hanging DOM element.

 <div id="app">
  <mycomponent></mycomponent>
  <my-component></my-component>
</div>
<script>
 was app = new Vue ({
  on: '#app'
  data: {
  },
  components: {
   'my-component': {
    template: `<div> This is a partial custom components, only </ div> 'in the present example Vue,
   }
  }
 })
</script>

Directly Vue.component () to create components, all instances of Vue can be used. You can also register only the components themselves can be used in certain instances Vue.

was app = new Vue ({
  on: '#app'
  data: {
  },
  components: {
   'my-component': {
    template: `<div> This is a partial custom components, only </ div> 'in the present example Vue,
   }
  }
 })

Requirements Template

Note: The template assembly can have only one root element. The following case is not allowed.

template: `<div> This is a partial custom components, only </ div> In the present example Vue
      <button>hello</button>`,

Components data must be a function

As can be seen, the incoming configure and create instances almost Vue registration component, but there are also different, which is a data property must be a function.
This is because if, as Vue instance as passing an object, since the object type JS variable is actually stored is a reference to the object, so that when a plurality of such assemblies, share data, resulting in a component data change will cause changes in the other components of the data.

And use a function that returns an object, every time you create a new object will use components, so that the problem of shared data will not appear here.

About DOM parsing templates

When using the DOM as a template (for example, el option to mount on an existing element), you will be subject to some limitations of HTML, because only in Vue browser parsing and template contents in order to obtain standardized HTML. Especially as these elements <ul>, <ol>, <table>, <select> element limits that can be wrapped in it, and some, like <option> This element can only occur within certain other elements.

When custom components in restricted use these elements can lead to problems, such as:

<table>
 <my-row>...</my-row>
</table>

Custom Component <my-row> is considered invalid content, thus rendering time will result in an error. At this time you should use special attributes is:

<table>
 <tr is="my-row"></tr>
</table>

In other words, standard HTML, some elements can only be placed in a particular child element, while others can only exist in specific elements of the parent element. For example in the table can not be placed div, tr parent element and the like can not div. So, when using a custom label, the label name or names of those labels, but you can fill in a self-names defined components is property tag.

Note that if you use a string template from one of the following sources, these restrictions do not apply:

<Script of the type = "text / the X-Template-">
JavaScript inline template string
.vue components
of which the first two templates are not Vue official recommendation, so under normal circumstances, only a single file component .vue can ignore this situation .

The component properties and events

Use in html element, there will be some properties, such as class, id, can also bind the event, custom components is also possible. When a component is used in other properties, and events custom components, sub-assemblies will use for data exchange and parent component.
<img src = "/ assets / images / props-events.png" />

As shown above, the communication between the props Sons assembly is down, events up, down through the parent attribute data transfer assembly props Events to send a message to the parent component subassembly, the subassembly through the event.
For example, a sub-assembly required data, within the definition of a prop property, then the parent component as specified characteristic value as to the html element, convey your own data attributes to attribute this sub-component.
And when the internal subassembly what happened, it is exposed through a custom event data to put this matter involved, the parent component for processing.

<my-component v-bind:foo="baz" v-on:event-a="doThis(arg1,...arg2)"></my-component>

Code above,

foo is <my-component> components inside a prop attribute definition, baz data attribute is a parent element,
Event is an event-A subassembly defined, doThis method is a parent component of
the process is such:

Parent component to foo baz data transmitted through the prop to the subassembly;
interior subassembly obtained value of foo, can perform the corresponding operation;
when the internal subassembly has changed, it is desirable parent component to know when to use the code trigger event -a event, some of the data sent to
the parent component is bound to the event handler doThis method, a data transmission subassembly, is passed as a parameter to come doThis method
then can parent component based on these data, the appropriate action

Properties Props

Vue assembly to declare a property by props own property, then you can drive a parent component to pass data.

Vue.component ( 'mycomponent', {
  template: '<div> This is a custom components, the parent content is passed to me: {{myMessage}} </ div>',
  props: ['myMessage'],
  data () {
   return {
    message: 'hello world'
   }
  }
 })

Then call the component

<div id="app">
  <mycomponent my-message="hello"></mycomponent>
</div>

Note that since HTML is case-insensitive characteristic, the transmission property values, should be converted into myMessage kebab-case (separated by hyphens formula) my-message = "hello".

Binding attribute values v-bind
said here about the v-bind a binding characteristic property values: Under normal circumstances, the use of v-bind to the element characteristic (attribute) value is passed, will Vue "Content" in the expression as a formula.
such as:

<div attr="message">hello</div>

Above this, attr characteristics div element value is the message.

And this

<div v-bind:attr="message">hello</div>

there should be a message attribute data of Vue example, attr div element characteristics of such value is the value of this attribute message.

The reason why is general, because of class and style characteristics is not the case. With v-bind: class and normal class passed the class name, the effect is the same, because for these two features, Vue uses a merger rather than a replacement principle.

Dynamic binding characteristic value

According to the above, the desired properties of the parent component is bound to the sub-assembly should be used v-bind, so that, when the parent components to reflect data changes subassembly.
Note, different attributes transmitted to the sub-assembly in accordance with the parent component, when the change in the property sub-assembly, there are two cases:

When the parent component is passed a reference type attribute, change the properties in the subassembly cause changes in the properties of the respective parent element.

  <div id="app2">
   <Div> This is parentArray parent element: {{parentArray}} </ div>
   <my-component :child-array="parentArray"></my-component>
  </div>
  <script>
   Vue.component('my-component', {
    template: `
    <Div> This subassembly is received childArray parent components pass values: {{childArray}} <br>
      <button type="button" @click="changeArray">
      Click on me to change parentArray parent element </ button>
     </div>`,
    props: ['childArray'],
    data () {
     return {
      counter: 1
     }
    },
    methods: {
     changeArray () {
      this.childArray.push(this.counter++)
     }
    }
   })
   new view ({
    the '# app2'
    data: {
     parentArray: []
    }
   })
  </script>

When the transfer assembly is substantially the parent type, change this property subassembly error. The correct approach is, when the bound property values ​​in the parent component, plus .sync modifier.

<my-component :child-array.sync="parentArray"></my-component>

Then change the properties in the subassembly

  methods: {
   changeArray () {
    this.counter++
    this.$emit('update:childArray', this.counter)
   }
  }

Subassemblies hope incoming prop operate

Generally, it is not recommended to operate the property passed to the parent element in the subassembly. If there is such a demand, it can be:

Passing a basic parent component type value, it can create a new attribute in the sub-assembly, and to initialize the value passed in, then this can operate the new attribute

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

Parent component type passed a reference value, in order to avoid changing the corresponding data in the parent component, preferably a reference to the type copy. Complex situations, certainly should be deep copy.

Subassembly to pass the correct type of value

Likewise the above reasons, the static characteristic value passed to the sub-assembly, which will put him as a string.

<! - passed a string of "1" ->
<comp some-prop="1"></comp>

Subassembly, the value of the property is a string of "1" instead of number 1. To transfer the correct value should be transmitted using v-bind, so that the values ​​can be passed as an expression processing, instead of a string.

<! - transmitting actual number 1 ->
<comp v-bind:some-prop="1"></comp>

Prop verification

We can add props to verify properties of the component when incoming data does not meet the requirements, Vue will be issued a warning.

Vue.component('example', {
 props: {
  // base type detection ( `null` can mean any type)
  propA: Number,
  // various types
  propB: [String, Number],
  // and must pass a string
  Ocean: {
   type: String,
   required: true
  },
  // figures, have default values
  propD: {
   type: Number,
   default: 100
  },
  // Default array / object should be returned by a function factory
  near: {
   type: Object,
   default: function () {
    return { message: 'hello' }
   }
  },
  // custom validation function
  propF: {
   validator: function (value) {
    return value > 10
   }
  }
 }
})

It may be a native type constructors below:

String
Number The
Boolean
Function
Object
the Array
the Symbol
type may be a custom constructor function, using instanceof detected.

 // constructor custom Person
 function Person(name, age) {
  this.name = name
  this.age = age
 }
 Vue.component('my-component', {
  template: `<div> Name: {{person-prop.name}}, Age: {{person-prop.age}} </ div>`,
  props: {
   person-prop: {
    type: Person // specified type
   }
  }
 })
 new view ({
  the '# app2'
  data: {
   person: 2 // Number of incoming types will complain
  }
 })

Non-Prop type of property

Data- like may be added in the beginning of html tags as custom properties, custom components to add arbitrary attributes. Not just data- * form to do so, Vue will put the property on the root element of self-defined components. A custom template components can have only one root element.

Prop cover non-property

If the value passed to the parent component properties in a subcomponent of non prop, then this value overrides the properties sub-assembly template.

<div id="app3">
  <my-component2 att="helloParent"></my-component2>
</div>
<script>
 Vue.component('my-component2', {
  template: `<div att =" helloChild "> the original characteristics of the sub-assembly is covered </ div>`
 })
 new view ({
  the '# app3'
 })
</script>

Rendering the above result, att div attribute is helloParent.
Note: As already mentioned, covers the principles and style for class not applicable, instead of using the combined principle (Merge) a.

<div id="app3">
  <my-component2 att="helloParent" class="class2" style="color: red;"></my-component2>
</div>
<script>
 Vue.component('my-component2', {
  template: `<div att =" helloChild "class =" class1 "style =" background: yellow; "> the original characteristics of the sub-assembly is covered </ div>`
 })
 new view ({
  the '# app3'
 })
</script>

The above rendering result, div class name class1 class2, inline style is color: red; background: yellow ;.

Custom Event

By prop attribute, data can be transferred to the parent component subassemblies, and custom events subassembly is used inside the data reported to the parent component.

<div id="app3">
  <my-component2 v-on:myclick="onClick"></my-component2>
</div>
<script>
 Vue.component('my-component2', {
  template: `<div>
  <Button type = "button" @ click = "childClick"> click on my custom event trigger </ button>
  </div>`,
  methods: {
   childClick () {
    this. $ emit ( 'myclick', 'This is my exposed to data', 'This is my data exposed to 2')
   }
  }
 })
 new view ({
  the '# app3'
  methods: {
   onClick () {
    console.log(arguments)
   }
  }
 })
</script>

As shown above, it consists of the following steps:

Subassembly in the custom events and their methods of data necessary to issue the following code sent by

this. $ emit ( 'myclick', 'This is my exposed to data', 'This is my data exposed to 2')

The first parameter is the name of self-defined events
behind the argument is the turn of the data you want to send out
parent component using the v-on for the event binding processor

<my-component2 v-on:myclick="onClick"></my-component2>

Thus, the method Vue instance methods can be passed in the call parameters

Note: When using the v-on binding events approach, should not pass into any arguments, but write directly to v-on: myclick = "onClick", otherwise, sub-assemblies exposed data will not be able to get

Binding native events

If you want to monitor a native event on the root element of a component. You can use .native modified v-on

<my-component v-on:click.native="doTheThing"></my-component>

Explore the v-model

v-model can achieve two-way data binding form controls, its principle is to use the binding properties and events to achieve. For example, input controls. Without the use of v-model, can be achieved by two-way data binding:

<div id="app4">
  <input type="text" v-bind:value="text" v-on:input="changeValue($event.target.value)">
  {{text}}
 </div>
 <script>
   new view ({
    the '# app4'
    data: {
     text: '444'
    },
    methods: {
     changeValue (value) {
      this.text = value
     }
    }
   })
 </script>

The above code also achieved two-way data binding. Its essence is this:

The characteristics of the input value of the instance attribute Vue bound to text, text change will change the content of the input
and the input form to a event handler method Vue example, this method changes according to an input parameter Vue text` value of
the corresponding, typing in the input, the input event is triggered, the event.target.value passed to this method, and finally realize the effect of changing the binding data.
The v-model is syntactic sugar on top of this way, that is the wording of the above packages for a moment, to facilitate our use.

Use custom events to create a custom form input components

Understanding of insider v-model, this effect can also be used on a custom form components.
It can only be achieved with a simple input form input component of hello.

<div id="app5">
  <my-component3 v-model="hello"></my-component3>
  <div>{{hello}}</div>
</div>
<script>
 Vue.component('my-component3', {
  template: `<input ref="input" type="text" :value="value" @input="checkInput($event.target.value)">`,
  props: ['value'],
  methods: {
   checkInput (value) {
    was hello = 'hello'
    if (!hello.includes(value)) {
     this.$emit('input', hello)
     this.$refs.input.value = hello
    } else {
     this.$emit('input', value)
    }
   }
  }
 })
 new view ({
  the '# app5'
  data: {
   hello: ''
  }
 })
</script>

Custom components of v-model

By default, a component of v-model uses the property value and the input events, such as radio buttons, check boxes or the like input type may be used as the attribute value to other purposes. model option to avoid this conflict:

Vue.component('my-checkbox', {
 model: {
  prop: 'checked', // checked to the characteristics of the input
  event: 'change' type // custom event triggers for change
 },
 props: {
  checked: Boolean,
  // this allows using the `value` prop for a different purpose
  value: String
 }
})

Such set,

<my-checkbox v-model="foo" value="some value"></my-checkbox>

The above code is equivalent to

<my-checkbox :checked="foo" @change="val => { foo = val }" value="some value"></my-checkbox>

Actual use, and before the difference is:

The sub-assembly receives external data attributes to prop checked
when issuing an event to the parent component should be changed to change the type of event

Vue.component('my-component3', {
  template: `<input ref="input" type="text" :value="checked" @input="checkInput($event.target.value)">`,
  props: [ 'checked'], // the attribute name change
  model: {
   prop: 'checked',
   event: 'change'
  },
  methods: {
   checkInput (value) {
    was hello = 'hello'
    if (!hello.includes(value)) {
     this. $ emit ( 'change', hello) // event type change
     this.$refs.input.value = hello
    } else {
     this. $ emit ( 'change', value) // event type change
    }
   }
  }
 })

Dynamic Components

By using the reserved <component> element, dynamically bind to it is characteristic, that allows the plurality of components using the same mount point, and dynamic switching:

 <div id="app6">
  <select v-model="currentComponent">
   <option value="home">home</option>
   <option value="post">post</option>
   <option value="about">about</option>
  </select>
  <component :is="currentComponent"></component>
 </div>
 <script>
   new view ({
    the '# APP6'
    data: {
     currentComponent: 'home'
    },
    components: {
     home: {
      template: `<header> This is the home assembly </ header>`
     },
     post: {
      template: `<header> This is a post assembly </ header>`
     },
     about: {
      template: `<header> component which is about </ header>`
     }
    }
   })
</script>

You can also bind directly to the component object:

was Home = {
 template: `<header> This is the home assembly </ header>`
}
new view ({
 the '# APP6'
 data: {
  currentComponent: Home
 }
})

Retention components switched-out, to avoid re-rendering

If the switched-out assembly remains in memory, or can retain its status to avoid re-rendering. For this purpose, a keep-alive add command parameters:

<keep-alive>
 <component :is="currentComponent">
  <! - inactive components will be cached! ->
 </component>
</keep-alive>

Use slot distribute content

And finally to the last of the basics. Official website written in great detail.

Single slot

Many use the components used above is this:

<component></component>

That component is empty, do not place any text or elements. But the native html elements can all be nested, div which put table
or something. Between custom tag assembly may be opened and closed to place the content, but requires the use of slot when defining component.

slot is equivalent to set up a sub-assembly place, If you call it, to between its opening and closing tags put something, put it into the slot in these things.

When there is no slot in the sub-assembly, something placed within parent components subassembly tag is dropped;
the slot label content subassembly may be placed, when the parent component content is not placed in the subassembly tag, the slot contents will rendered;
when the content of the parent assembly is placed in a subassembly tag, the slot contents are discarded
template subassemblies:

<div>
 <H2> I am a header sub-component of </ h2>
 <slot>
  Is displayed only when the content is not to be distributed.
 </slot>
</div>

Parent component template:

<div>
 <H1> is the title of my parent component </ h1>
 <my-component>
  <P> This is some initial content </ p>
 </my-component>
</div>

Rendering results:

<div>
 <H1> is the title of my parent component </ h1>
 <div>
  <H2> I am a header sub-component of </ h2>
  <P> This is some initial content </ p>
 </div>
</div>

Named slot

slot can be many. Then the sub-assembly for extra content in the parent component is placed on how to put each slot in it? When the subassembly is to give each a name slot name, parent component placing extra elements, the properties of each slot to the assigned slot of a representative of the name. At that time, the extra content will be based on their slot has a corresponding attribute to look for the name of the slot elements.

note:

Sub-components can have an anonymous slot, when the distribution of the extra content not find the corresponding slot, it will enter there
if sub-components are not anonymous slot, when the distribution of the extra content not find the corresponding slot, will discarded
For example, suppose we have an app-layout component that template is:

<div class="container">
 <header>
  <slot name="header"></slot>
 </header>
 <main>
  <slot></slot>
 </main>
 <footer>
  <slot name="footer"></slot>
 </footer>
</div>

Parent component template:

<app-layout>
 <H1 slot = "header"> There may be a page title </ h1>
 <P> paragraph a main content. </ P>
 <P> Another major sections. </ P>
 <P slot = "footer"> Here are some contact information </ p>
</app-layout>

Rendering results:

<div class="container">
 <header>
  <H1> There may be a page title </ h1>
 </header>
 <main>
  <P> paragraph a main content. </ P>
  <P> Another major sections. </ P>
 </main>
 <footer>
  <P> Here are some contact information </ p>
 </footer>
</div>

Scope slot

Scope slot is a slot slot, but he can pass the data to a specific element to the parent element, then has a parent component to determine how to render the data.

First, slot subassembly need to have some characteristics (prop)

 Vue.component('my-component4', {
   template: `<div>
    <slot :text="hello" message="world"></slot>
   </div>`,
   data () {
    return {
     hello: [1,'2']
    }
   }
  })

When calling parent component sub-assembly, required to add a template element in it, and this template element having a scope attribute

<div id="app7">
 <my-component4>
  <template scope="props">
  </template>
 </my-component4>
 </div>

Value scope characteristics, on behalf of all the objects pass over the subcomponents of data. Equivalent to

props = {
  text: '',
  message: ''
}

Finally, you can render the parent component sub-assemblies pass over the data in the template

 <div id="app7">
  <my-component4>
   <template slot-scope="props">
    <span>{{props.text}}</span>
    <span>{{props.message}}</span>
   </template>
  </my-component4>
 </div>

Vue will support the latest property scopes slot deconstruction. Therefore, the above code can be abbreviated as:

 <div id="app7">
  <my-component4>
   <template slot-scope="{text, message}">
    <span>{{text}}</span>
    <span>{{message}}</span>
   </template>
  </my-component4>
 </div>

Scope slot is the slot, just added more features, then the parent component was more than some treatment.

That is more personal understanding of the components of the Vue, we want to help

Guess you like

Origin www.cnblogs.com/superheaaya/p/12204293.html