Corresponding knowledge points for Vue component development

Corresponding knowledge points for Vue component development

1. Component registration

1.1 Global Registration

Register through the Vue.component('component name',{}) method; any instance of a globally registered component can be used.
The basic example code is as follows:

  <div id="app">
    <button-counter></button-counter>
  </div>
  
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    Vue.component('button-counter', {
    
    
      // data 是一个函数 返回后一个对象,数据存储于对象中
      data: function(){
    
    
        return {
    
    
          count: 0
        }
      },
      // 组件的模板必须是只有一个根元素,内容也可以是模板字符(``)串形式
      template: '<button @click="handle">点击了{
    
    {count}}次</button>',
      methods: {
    
    
        handle: function(){
    
    
          this.count += 2;
        }
      }
    })
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        
      }
    });
  </script>

1.2 Partial registration

Partially registered components can only be used in the current instance.
The basic example code is as follows:

  <div id="app">
    <test-com></test-com>
  </div>
  
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    Vue.component('test-com',{
    
    
      // 不会显示helloworld,因为hello-world组件是在vm中注册的
      template: '<div>Test<hello-world></hello-world></div>'
    });
    var HelloWorld = {
    
    
      data: function(){
    
    
        return {
    
    
          msg: 'HelloWorld'
        }
      },
      template: '<div>{
    
    {msg}}</div>'
    };
   
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        
      },
      // 注册局部组件
      components: {
    
    
        'hello-world': HelloWorld,
      }
    });

2. Passing values ​​between Vue components

2.1 Pass value from parent component to child component

The parent component binds the corresponding data to the child component in the template, and uses props in the child component to receive the value passed by the parent component; for components directly embedded in html, if the hump form is used in props, when binding data You need to use the dash form to bind, but you don't need to consider this type of restriction when you use strings.

  <div id="app">
    <div>{
    
    {
    
    pmsg}}</div>
    <menu-item :menu-title='ptitle'></menu-item>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      父组件向子组件传值-props属性名规则
    */
    Vue.component('third-com', {
    
    
      props: ['testTile'],
      template: '<div>{
    
    {testTile}}</div>'
    });
    Vue.component('menu-item', {
    
    
      props: ['menuTitle'],
      template: '<div>{
    
    {menuTitle}}<third-com testTile="hello"></third-com></div>'
    });
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        pmsg: '父组件中内容',
        ptitle: '动态绑定属性'
      }
    });
  </script>

2.2 Subcomponents pass values ​​to parent components

$emit()Use the trigger event in the child component $emit(). The first parameter is the custom event name and the second parameter is the data to be passed. The parent component needs to use v-on to listen to the event of the child component. The event name is the same as the custom one in the child component. The event names are consistent.

  <div id="app">
    <div :style='{fontSize: fontSize + "px"}'>{
    
    {
    
    pmsg}}</div>
    <menu-item @enlarge-text='handle($event)'></menu-item>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      子组件向父组件传值-携带参数
    */
    
    Vue.component('menu-item', {
    
    
      props: ['parr'],
      template: `
        <div>
          <button @click='$emit("enlarge-text", 10)'>扩大父组件中字体大小</button>
        </div>
      `
    });
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        pmsg: '父组件中内容',
        fontSize: 10
      },
      methods: {
    
    
        // val为$emit()中传递过来的参数(可以是对象、数组)
        handle: function(val){
    
    
          // 扩大字体大小
          this.fontSize += val;
        }
      }
    });
  </script>

2.3 Passing values ​​between sibling components

The transfer of data between brothers needs to rely on the event center to transfer data through the event center (provide event center var hub = new Vue()); the data transfer party triggers hub. emit (method name, transferred data) through an event, and receives The data side triggers the hub. emit(method name, passed data) in the mounted () hook function, and the receiving data side triggers the hub in the mounted(){} hook function.e m i t ( method name , passed data ) , receiving data side , through m o n t e d ( ) _ _ _Trigger the h u b .on () method name in the hook function ; the event can be destroyed after the data transfer is completed, and the data cannot be transferred after being destroyed by the hub.$off() method name.

  <div id="app">
    <div>父组件</div>
    <div>
      <button @click='handle'>销毁事件</button>
    </div>
    <test-tom></test-tom>
    <test-jerry></test-jerry>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      兄弟组件之间数据传递
    */
    // 提供事件中心
    var hub = new Vue();

    Vue.component('test-tom', {
    
    
      data: function(){
    
    
        return {
    
    
          num: 0
        }
      },
      template: `
        <div>
          <div>TOM:{
     
     {num}}</div>
          <div>
            <button @click='handle'>点击</button>
          </div>
        </div>
      `,
      methods: {
    
    
        handle: function(){
    
    
          hub.$emit('jerry-event', 2);
        }
      },
      mounted: function() {
    
    
        // 监听事件
        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'>点击</button>
          </div>
        </div>
      `,
      methods: {
    
    
        handle: function(){
    
    
          // 触发兄弟组件的事件
          hub.$emit('tom-event', 1);
        }
      },
      mounted: function() {
    
    
        // 监听事件
        hub.$on('jerry-event', (val) => {
    
    
          this.num += val;
        });
      }
    });
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        
      },
      methods: {
    
    
        handle: function(){
    
    
          hub.$off('tom-event');
          hub.$off('jerry-event');
        }
      }
    });
  </script>

3. Component slots

The biggest feature of components is reusability, and good use of slots can greatly improve the reusability of components. Set the default content in the child component, and display the default content when the parent component does not pass content to the child component.

3.1 Anonymous slots

Set the default content in the child component, and display the default content when the parent component does not pass content to the child component.

  <div id="app">
    <alert-box>有bug发生</alert-box>
    <alert-box>有一个警告</alert-box>
    <alert-box></alert-box>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      组件插槽:父组件向子组件传递内容
    */
    Vue.component('alert-box', {
    
    
      template: `
        <div>
          <strong>ERROR:</strong>
          <slot>默认内容</slot>
        </div>
      `
    });
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        
      }
    });
  </script>

3.2 Named slots

Use the name in the slot tag to bind the corresponding element; and use the template tag to merge and pass multiple information to a slot.

  <div id="app">
    <base-layout>
      <p slot='header'>标题信息</p>
      <p>主要内容1</p>
      <p>主要内容2</p>
      <p slot='footer'>底部信息信息</p>
    </base-layout>

    <base-layout>
      <template slot='header'>
        <p>标题信息1</p>
        <p>标题信息2</p>
      </template>
      <p>主要内容1</p>
      <p>主要内容2</p>
      <template slot='footer'>
        <p>底部信息信息1</p>
        <p>底部信息信息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>
            <slot name='header'></slot>
          </header>
          <main>
            <slot></slot>
          </main>
          <footer>
            <slot name='footer'></slot>
          </footer>
        </div>
      `
    });
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        
      }
    });
  </script>

3.3 Scoped slots

Scope slots can be processed by the parent component on the child component, which can not only reuse the slot of the child component, but also make the slot content inconsistent.
Specific use: define slots in the child component, pass the data to the parent component through property binding, and use the template tag and its slot-scope attribute in the parent component to obtain the data of the child component . For example, if the child component binds the :info attribute, use slot-scope='father' to receive it in the parent component ; when the parent component needs to process the data, obtain the data through father.info and perform corresponding operations.

  <div id="app">
    <fruit-list :list='list'>
      <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('fruit-list', {
    
    
      props: ['list'],
      template: `
        <div>
          <li :key='item.id' v-for='item in list'>
            <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>

Guess you like

Origin blog.csdn.net/weixin_42371354/article/details/104932657