vue之组件的简单使用

1.背景

2.组件的简单使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
    <script src="../js/vue.js"></script>
</head>
<body>
<h2>组件使用的基本步骤</h2>
<pre>
    1.创建组件构造器 const componentMy = Vue.extend({ template:'html模板'})
    2.注册组件  Vue.component('c-my', componentMy)
    3.使用组件 写一组标签 c-my

这三步的执行分析:

1.Vue.extend():
调用Vue.extend()创建的是一个组件构造器。
通常在创建组件构造器时,传入template代表我们自定义组件的模板。
该模板就是在使用到组件的地方,要显示的HTML代码。

2.Vue.component():
调用Vue.component()是将刚才的组件构造器注册为一个组件,并且给它起一个组件的标签名称。
所以需要传递两个参数:1、注册组件的标签名 2、组件构造器

3.组件必须挂载在某个Vue实例下,否则它不会生效。

</pre>
<div id="app">
    <!-- <div>
         <h4>我是主键01</h4>
         你好,我是自定义的组件
     </div>-->
    <!-- 3.使用组件-->
    <c-my></c-my>
</div>
<script>
    // 1.创建组件构造器
    const componentMy = Vue.extend({
        // 相当于一个模板
        template: '<div>' +
            '        <h4>我是主键01</h4>' +
            '        你好,我是自定义的组件' +
            '    </div>'
    })
    // 2.注册组件
    Vue.component('c-my', componentMy)

    let app = new Vue({
        el: '#app'
    })
</script>
</body>
</html>
View Code

3.全局组件与局部组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
    <script src="../js/vue.js"></script>
</head>
<body>
<h2>局部组件与全局组件</h2>
<pre>


</pre>
<div id="app">
    <!-- 3.使用组件-->
    <c-my></c-my>
</div>
<script>
    // 1.创建组件构造器
    const componentMy = Vue.extend({
        // 相当于一个模板
        template: '<div>' +
            '        <h4>我是主键01</h4>' +
            '        你好,我是自定义的组件' +
            '    </div>'
    })
    // 2.注册组件(在这里注册的是 全局 组件,在任意一个vue实例下都可以使用)
    // Vue.component('c-my', componentMy)

    let app = new Vue({
        el: '#app',
        // 2.注册组件(在这里注册的是 局部 组件,只能在id=app下面使用才有效)
        components: {
            'c-my': componentMy
        }
    })
</script>
</body>
</html>
View Code

完美!

原文地址:https://www.cnblogs.com/newAndHui/p/13838960.html