【Vue笔记】Vue组件的创建、使用以及父子组件数据通信常见的几种方式

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

这篇文章主要介绍Vue组件的创建、使用以及父子组件数据通信常见的几种方式。

目录

一、Vue组件的使用

1.1、局部组件

1.2、全局组件

1.3、动态组件组件动态切换

1.4、缓存组件

1如何缓存组件

2如何更新组件

1.5、父组件传递数据给子组件

1props属性传递数据

2props数据类型校验

1.6、子组件回传数据给父组件

1.7、子组件回调父组件方法


一、Vue组件的使用

1.1、局部组件

  • 局部组件创建的组件只能够在当前Vue实例中使用作用域更小。
  • 局部组件的注册
    • 第一步定义局部组件对象对象里面使用【template】属性定义组件的模板当组件里面也可以使用其他Vue的所有属性和方法。
    • 第二步在Vue实例里面使用【components】属性注册局部组件。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>局部组件</title>
</head>
<body>

<div id="app">
    <h3>Vue局部组件</h3>
    <!-- 使用局部组件 -->
    <scope-component></scope-component>
</div>

<div id="app2">
    <h3>Vue局部组件</h3>
    <div>{{ message }}</div>
    <!-- 无法使用第一个实例的局部组件不会报错只是不生效 -->
    <scope-component></scope-component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建局部组件
    const scopeComponent = {
        template: `<div>
            <h4>这是局部组件</h4>
        </div>`
    };
    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app',
        // 注册局部组件
        components: {
            scopeComponent
        }
    });

    // 创建第二个Vue实例对象
    const vm2 = new Vue({
        el: '#app2',
        data() {
            return {
                message: 'Hello World'
            }
        }
    });
</script>
</body>
</html>

1.2、全局组件

  • 全局组件创建的组件是直接挂在到整个Web应用程序的Vue实例上面可以在任意的作用域里面使用创建的全局组件。
  • 全局组件的注册
    • ​​​​​​​第一步使用【Vue.component(组件名称组件配置项)】方法注册全局组件。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全局组件</title>
</head>
<body>

<div id="app">
    <h3>Vue全局组件: 第一个vue实例对象</h3>
    <!-- 使用全局组件 -->
    <global-component></global-component>
</div>

<div id="app2">
    <h3>Vue全局组件: 第二个vue实例对象</h3>
    <!-- 可以使用第一个实例的全局组件全局组件所有Vue实例共享 -->
    <global-component></global-component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建全局组件
    const globalComponent = {
        template: `<div>
            <h4>这是全局组件</h4>
        </div>`
    };
    // 注册全局组件
    Vue.component('global-component', globalComponent);
    
    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app'
    });

    // 创建第二个Vue实例对象
    const vm2 = new Vue({
        el: '#app2'
    });
</script>
</body>
</html>

1.3、动态组件组件动态切换

Vue中提供了【is】属性这个属性可以根据传递的【组件名称】动态的切换显示的不同组件的内容一般来说都是结合【<component>】标签一起使用当然你也可以用在普通的HTML标签上面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动态组件</title>
</head>
<body>

<div id="app">
    <h3>Vue动态切换组件</h3>
    <div>
        <button @click="showComp('firstComponent')">显示组件01</button>
        <button @click="showComp('secondComponent')">显示组件02</button>
        <button @click="showComp('thirdComponent')">显示组件03</button>
    </div>
    <!-- 动态切换组件 -->
    <component :is="compName"></component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建局部组件
    const firstComponent = {
        data() {
            return {
                message: ''
            }
        },
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h4>这是firstComponent组件</h4>
            <input type="text" v-model="message">
        </div>`
    };
    const secondComponent = {
        data() {
          return {
              message: ''
          }
        },
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h4>这是secondComponent组件</h4>
            <input type="text" v-model="message">
        </div>`
    };
    const thirdComponent = {
        data() {
            return {
                message: ''
            }
        },
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h4>这是thirdComponent组件</h4>
            <input type="text" v-model="message">
        </div>`
    };

    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app',
        components: {
            firstComponent,
            secondComponent,
            thirdComponent
        },
        data() {
            return {
                compName: firstComponent
            }
        },
        methods: {
            showComp(val) {
                this.compName = val;
            }
        }
    });
</script>
</body>
</html>

动态切换组件的效果如下所示

1.4、缓存组件

动态组件在切换的过程中每一次切换都是重新创建一个组件有些时候其实没有必要重新创建新的组件可以利用已经创建的组件显示就可以所以Vue官方也考虑到了这一点提供了一个【<keep-alive>】标签这个标签的作用就是将已经的组件缓存起来下一次显示这个组件的时候不会重新创建而是直接使用缓存中的组件。

1如何缓存组件

如何使用【<keep-alive>】标签缓存组件

  • 我们只需要在显示组件的位置使用【<keep-alive>】标签将其包裹起来就可以完成组件的缓存功能。
<!-- 缓存组件 -->
<keep-alive>
    <!-- 动态切换组件 -->
    <component :is="compName"></component>
</keep-alive>
  • 通过上面的步骤再次访问我们的组件可以发现之前已经创建的组件再次切换的时候该组件会保持之前的状态。

  • 从上图可以看到我们在组件输入框里输入一些内容然后再次切换到这个组件这个输入框的内容是不会被刷新掉而是保持之前组件的状态这个就是组件被缓存起来了。

2如何更新组件

组件缓存虽然可以减少DOM的渲染但是有时候我们可能会有一些需求那就是在组件切换的时候其中某个组件需要更新而其他组件不需要更新那么应该如何更新那一个组件呢

Vue也考虑到了这一点所以提供了钩子函数如果需要更新某个缓存组件的部分内容可以在【activitated()】钩子函数里面进行数据的更新操作。

  • 【activitated()】钩子函数每一次访问组件的时候这个钩子函数都会执行一次。
const secondComponent = {
    // 在 onActivated 钩子函数中更新对应的数据
    activated() {
        // 在这个函数里面可以根据实际需要进行业务处理操作
        this.message = ''
    },
    data() {
      return {
          message: ''
      }
    },
    template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
        <h4>这是secondComponent组件</h4>
        <input type="text" v-model="message">
    </div>`
};

1.5、父组件传递数据给子组件

Web应用程序拆分成了一个一个的Vue组件那么Vue组件之间的数据交互就成了一个问题好在Vue官方也给我们通过了非常好用的父子组件通信的机制下面介绍父组件如何传递数据给子组件。

注意props是单向数据流的也就是说数据只能够从父组件传递到子组件而不能够从子组件传递到父组件。

1props属性传递数据

  • Vue中父组件要给子组件传递数据是通过【props】属性来实现。
  • 父组件在父组件里面通过在子组件标签上使用对应的属性名称传递数据。
  • 子组件在子组件里面通过定义【props】属性指定需要接收的数据名称。
  • props可以是一个字符串数组数组中的每一个元素表示父组件传递过来的一个数据变量名称
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父组件传递数据子组件</title>
</head>
<body>

<div id="app">
    <h3>Vue组件通信父组件传递数据子组件</h3>
    <first-component :custom-data="message"></first-component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建局部组件
    const firstComponent = {
        // 通过props定义父组件的数据
        props: ['customData'],
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h3>这是firstComponent组件</h3>
            <h4>这是父组件传递的数据{{ customData }}</h4>
        </div>`
    };

    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app',
        components: {
            firstComponent
        },
        data() {
            return {
                message: 'this is data of parent.'
            }
        }
    });
</script>
</body>
</html>

2props数据类型校验

  • 前面说了props可以是一个字符串数组其实它也可以是一个对象并且可以给props属性设置每一个属性的数据类型、默认值。
  • props采用对象的格式对应中的每一个属性又是一个对象每一个属性对象可以定义【type】和【default】两个属性值分别表示数据类型和默认值。
  • type属性常见的数据类型有String、Number、null、Boolean、Object、Array、Function、Promise注意type可以是数组包含多个数据类型只要满足其中一个即可。
  • default属性对于Object、Array、Function类型需要使用一个工厂方法来设置默认值其余的直接设置默认值即可。
// 创建局部组件
const firstComponent = {
    // 通过props定义父组件的数据
    props: {
        customData: {
            type: Number,
            default: 520
        },
        userName: {
            type: [String, null],
            default: ''
        },
        objectType: {
            type: Object,
            default: function () {
                return new Object()
            }
        },
        arrayType: {
            type: Array,
            default: function () {
                return []
            }
        },
        funType: {
            type: Function,
            default: function () {
                return null
            }
        }
    }
};

1.6、子组件回传数据给父组件

子组件如果需要将数据传递到父组件那么只能够通过触发事件的形式来实现。大致思想是子组件通过【$emit()】方法向父组件抛出一个事件父组件监听这个事件一旦子组件抛出事件之后那么父组件就可以执行这个事件从而获取到子组件传递的数据。

  • 【$emit()方法】Vue中提供了【$emit(事件名称参数[可以多个])】方法这个方法作用向父组件发出一个事件。
  • 注意事项
    • ​​​​​​​$emit()方法中第一个参数定义的事件名称只能够使用小写不能使用大写驼峰命名法规则否则不生效

案例代码如下所示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>子组件传递数据父组件</title>
</head>
<body>

<div id="app">
    <h3>Vue组件通信子组件传递数据父组件</h3>
    <!--
        子组件传递数据给父组件
        父组件监听handleEmitClick 事件采用中划线命名
     -->
    <first-component @getdata="getData"></first-component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建局部组件
    const firstComponent = {
        methods: {
            sendData() {
                this.$emit('getdata', '这是子组件传递的数据')
            }
        },
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h3>这是firstComponent组件</h3>
            <div><button @click="sendData">子组件回传数据($emit)</button></div>
        </div>`
    };

    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app',
        components: {
            firstComponent
        },
        methods: {
            // 父组件触发的事件
            getData(item) {
                console.log(item)
            }
        }
    });
</script>
</body>
</html>

1.7、子组件回调父组件方法

父组件和子组件除了通过【$emit()】方法来进行数据交互其实还可以通过回调事件来进行数据交互。大致思想是父组件将一个函数Function作为一个props属性传递给子组件然后在子组件执行这个Function函数即可这个过程本质就是子组件执行父组件中的函数。

  • 父组件将一个Function函数作为props属性传递给子组件执行。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>子组件回调父组件方法</title>
</head>
<body>

<div id="app">
    <h3>Vue组件通信子组件回调父组件方法</h3>
    <!--
        子组件传递数据给父组件
        父组件监听handleEmitClick 事件采用中划线命名
     -->
    <first-component :get-data="getData"></first-component>
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    // 创建局部组件
    const firstComponent = {
        props: {
          getData: {
              type: Function,
              default: null
          }
        },
        methods: {
            sendData() {
                // 回调父组件方法
                this.getData('这是子组件传递的数据')
            }
        },
        template: `<div style="height: 100px;width: 300px;background: antiquewhite;">
            <h3>这是firstComponent组件</h3>
            <div><button @click="sendData">子组件回调父组件方法</button></div>
        </div>`
    };

    // 创建Vue实例对象
    const vm = new Vue({
        el: '#app',
        components: {
            firstComponent
        },
        methods: {
            // 父组件触发的事件
            getData(item) {
                console.log(item)
            }
        }
    });
</script>
</body>
</html>

到此Vue中组件的创建和父子组件数据通信就介绍完啦。

综上这篇文章结束了主要介绍Vue组件的创建、使用以及父子组件数据通信常见的几种方式。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue