component

  • Components are one of the most powerful features of vue.js
  • Features A page is made up of different components
  • Components extend HTML elements and encapsulate reusable code

The component registration

Global registration

  • Format: Vue.component (” Component name “,{}) The first argument is the label name and the second argument is the option object

  • The reason for using components in a dash is because HTML is not case sensitive (i.e.

  • After the global component is registered, any Vue instance (component) can be used

      <div id="app">
         <! Data is a function. Because of the scope, the data of each component does not interfere with each other. 
        <button-counter></button-counter>
        <button-counter></button-counter>
        <button-counter></button-counter>
          <! 8, must use a dash to use components -->
               <! -- Component names are equivalent to HTML tags -->
         <hello-world></hello-world>
      </div>
    
    <script type="text/javascript">
        
        // if you use a camel name, you must use a dash to use the component
         Vue.component('HelloWorld', {
          data: function(){
            return {
              msg: 'HelloWorld'}},template: '<div>{{msg}}</div>'
        });
        
        Vue.component('button-counter', {
          // 1. The data value of the component parameter must be a function
          // This function also requires that an object be returned
          data: function(){
            return {
              count: 0}},
             
    The content of a component template can be a template string template: '
    < button@click ="handle"> click {{count}} times # 6 You can use components in a string template in a hump manner
    `
    .// Methods can also be defined in components methods: { handle: function(){ this.count += 2; }}})// Create the root instance var vm = new Vue({ el: '#app'.data: { sum:1}});
    </script> Copy the code
  • Global registration considerations

    • Data must return the structure of an object for a function (when data is a function, when the same component is used repeatedly, because each component has its own scope, each component is independent of each other and does not respond to each other)
    • Why can’t data be an object? If data is an object, it refers to a reference data type. When the same component is used repeatedly, the data of each component is the same address.

Local registration

  • A local component can only be used in the parent component (Vue instance) that registers it (e.g.

    )

  • An error is reported if used within the template string of a global component

      <div id="app">
          <my-component></my-component>
      </div>
    
    
    <script>
        // Define the template for the component
        var Child = {
          template: '
             
    A custom component!
    '
    } new Vue({ el:"#app" // Locally register the component components: { // will only be available in the parent template and must be registered on the instance to be used in HTML files 'my-component': Child } })
    </script> Copy the code

Transfer values between Vue components

Parent component passes value to child component

  • Use parent values in child components: Define properties on parent components and bind values to be passed

  • Use props to receive in the child component

  • Props is a single data stream and can only be used for parent to child applications

  • The difference between :title and no: is that the value passed by title is a string if it is not quoted

    Title, if quoted, is a dynamic variable used to pass data

      <div id="app">
        <div>{{pmsg}}</div>
         <! -- menu-item is nested in APP, so menu-item is subcomponent -->
         <! Pass a static value to the child component -->
        <menu-item title='Value from parent component'></menu-item>
        <! -- ptitle is the parent component of data and can be numbers, objects, arrays, etc. -->
        <menu-item :title='ptitle' content='hello'></menu-item>
      </div>
    
      <script type="text/javascript">
        Vue.component('menu-item', {
          // 3. The child component uses the props property to receive data from the parent component
          props: ['title'.'content'].data: function() {
            return {
              msg: 'Data for the child component itself'}},// Use the values passed by the parent component in the template
          template: '<div>{{msg + "----" + title + "-----" + content}}</div>'
        });
        var vm = new Vue({
          el: '#app'.data: {
            pmsg: 'Contents of parent component'.ptitle: 'Dynamically bound Properties'}});</script>
    Copy the code

Child components pass values to parent components

  • The child component fires an event with $emit() that fires a custom event bound to the parent component (i.e. the first argument to $emit())

  • The first argument to $emit() is the custom event name and the second argument is the data to pass

  • The parent waits for the child to fire the event

  • The child component passes data by calling the parent component’s methods, essentially calling functions to pass parameters

     <div id="app">
        <div :style='{fontSize: fontSize + "px"}'>{{pmsg}}</div>
         <! The parent component can monitor the event of the child component with v-ON. Here, the parent component can monitor the event of the child component with v-on.	
        <menu-item :parr='parr' @enlarge-text='handle($event)'></menu-item>
      </div>
      <script type="text/javascript" src="js/vue.js"></script>
      <script type="text/javascript">Vue.component_props ('menu-item', {props: ['parr'], template: '<div>
              <ul>
                <li :key='index' v-for='(item,index) in parr'>{{item}}</li>
              </ul>The first parameter is the name of the custom event. The second parameter is the data to be passed<button @click='$emit("enlarge-text", 5)'>Increase font size in parent component</button>
              <button @click='$emit("enlarge-text", 10)'>Increase font size in parent component</button>
            </div>`}); Var vm = new Vue({el: '#app', data: {PMSG: 'parent ', parr: ['apple','orange','banana'], fontSize: 10}, methods: {handle: function(val){this.fontSize += val; }}});</script>
    
    Copy the code

Brother to brother

  • Data is transferred between brothers through the event center, and data is transferred through the event center

    • Var hub=new Vue ()
  • The passing side fires the sibling’s hook function via the hub.$emit(method name, passed data) event

  • Receive data through, mounted () {hub $on (” name “, (receive passed data) = > {}}

  • No data can be passed after the event is destroyed with the name of the hub.$off() method

     <div id="app">
        <div>The parent component</div>
        <div>
          <button @click='handle'>Destruction of the event</button>
        </div>
        <test-tom></test-tom>
        <test-jerry></test-jerry>
      </div>
      <script type="text/javascript" src="js/vue.js"></script>
      <script type="text/javascript">
        /* Data transfer between sibling components */
        //1. Provide the event center
        var hub = new Vue();
    
        Vue.component('test-tom', {
          data: function(){
            return {
              num: 0}},template: ` < div > < div > TOM: {{num}} < / div > < div > < button @ click = 'handle' > click < / button > < / div > < / div > `.methods: {
            handle: function(){
              $emit(method name, data passed) emits an event from the hub.$emit(method name, data passed) emits an event from the other component
              hub.$emit('jerry-event'.2); }},mounted: function() {
           // Locate the hub.$on(mounted(){} hook)
            hub.$on('tom-event'.(val) = > {
              this.num += val; }); }}); Vue.component('test-jerry', {
          data: function(){
            return {
              num: 0}},template: ` < div > < div > JERRY: {{num}} < / div > < div > < button @ click = 'handle' > click < / button > < / div > < / div > `.methods: {
            handle: function(){
              $emit(method name, data passed) emits an event from the hub.$emit(method name, data passed) emits an event from the other component
              hub.$emit('tom-event'.1); }},mounted: function() {
            // Locate the hub.$on() {// locate the hub.$on() {// locate the hub
            hub.$on('jerry-event'.(val) = > {
              this.num += val; }); }});var vm = new Vue({
          el: '#app'.data: {},methods: {
            handle: function(){
              //4, the destruction event was destroyed by the hub.$off() method name
              hub.$off('tom-event');
              hub.$off('jerry-event'); }}});</script>
    
    Copy the code

Component slot

  • The most important feature of a component is its usability, and a good use of slots can greatly improve the reuse of components

  • The parent component passes content to the child component

Anonymous slot

  <div id="app">
    <! If no value is passed, the default value in slot will be used.  
    <alert-box>Have a bug in</alert-box>
    <alert-box>There is a warning</alert-box>
    <alert-box></alert-box>
  </div>

  <script type="text/javascript">/* Component slot: parent component passes content to child component */ Vue.component('alert-box', {template: '<div>
          <strong>ERROR:</strong># When the component is rendered, this<slot>The element will be replaced with "nested content in component tags". Slots can contain any template code, including HTML<slot>The default content</slot>
        </div>`}); var vm = new Vue({ el: '#app', data: { } });</script>
</body>
</html>

Copy the code

A named slot

  • If the slot tag has the attribute name, it is called a named slot; otherwise, it is called an anonymous slot

  • Matches the template
    in the component based on the attribute slot=’header’ in the tag

  • Using the
    tag wrap can pass multiple pieces of content without the template being rendered to the page

      <div id="app">
        <base-layout>
           <! The value of this slot must match the name value of the following slot components. If no match is found, the slot will be placed in an anonymous slot. 
          <p slot='header'>Header information</p>
          <p>Main Content 1</p>
          <p>Main Content 2</p>
          <p slot='footer'>Bottom Information</p>
        </base-layout>
    
        <base-layout>
          <! Template temporary package tag will not render to the page -->  
          <template slot='header'>
            <p>Title Message 1</p>
            <p>Title Message 2</p>
          </template>
          <p>Main Content 1</p>
          <p>Main Content 2</p>
          <template slot='footer'>
            <p>Bottom Information Information 1</p>
            <p>Bottom Information Information 2</p>
          </template>
        </base-layout>
      </div>
      <script type="text/javascript" src="js/vue.js"></script>
      <script type="text/javascript">Vue.component('base-layout', {template: '<div>
              <header>### 1<slot>The "name" attribute binding element specifies the name of the current slot<slot name='header'></slot>
              </header>
              <main>
                <slot></slot>
              </main>
              <footer>The rendering order of the named slots depends entirely on the template, not on the order of the elements in the parent component<slot name='footer'></slot>
              </footer>
            </div>`}); var vm = new Vue({ el: '#app', data: { } });</script>
    </body>
    </html>
    
    Copy the code

Scope slot

  • Parent component to child component content processing

  • Use the slot-scope property in the parent component to receive data on the property bound by the child component, and then process it.

      <div id="app">
        <! We need to use scope interpolation when we want li's style to be defined externally where the component is used, because there may be multiple places to use the component, but the style is not the same.  
        <fruit-list :list='list'>
           <! Insert slotProps ="slotProps"; insert slotProps ="slotProps"; insert slotProps (); 	
            <! -- Use slot-scope to receive data from the item property of the child component, and then use V-if to process data -->
          <template slot-scope='slotProps'> 
            <strong v-if='slotProps.info.id==3' class="current">
                {{slotProps.info.name}}		         
             </strong>
            <span v-else>{{slotProps.info.name}}</span>
          </template>
        </fruit-list>
      </div>
      <script type="text/javascript" src="js/vue.js"></script>
      <script type="text/javascript">Vue.component_props ('fruit-list', {// Use props to accept data from the parent component: ['list'], template: '<div>
              <li :key='item.id' v-for='item in list'>### 3, In the child component template,<slot>The element has a function like props (MSG =" XXX ") for passing data to the component. The ### slot can provide a default content, and if the parent component does not provide content for the slot, the default content will be displayed. If the parent provides content for the slot, the default content is replaced<slot :info='item'>{{item.name}}</slot>
              </li>
            </div>`}); var vm = new Vue({ el: '#app', data: { list: [{ id: 1, name: 'apple' },{ id: 2, name: 'orange' },{ id: 3, name: 'banana' }] } });</script>
    </body>
    </html>
    
    Copy the code

Vue – routing

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, encourage the author to create a better article, thank 🙏 everyone.