Vue组件基础(一) -- 组件的创建

这里简单介绍一下组件创建的三种方法
方式1: extend创建的组件

<script>
	//用一个变量接收extend创建的组件
	var com = Vue.extend({
		template: "<h3>这是我的第一个组件<h3>"
	})
	//将组件注册到Vue中
	Vue.component("first-component",com)
</script>

方式二:直接使用字面量对象的方式

<script>
	Vue.component("second-component",{
		template: "<h3>这是我的第二个组件<h3>"
	})
</script>

方式三:利用template元素标签创建

//先利用template元素标签创建组件模板 并给定id
<body>
	<template id="third">
	<div>
		<h3>这是我的第三个自定义组件</h3>
    </div>
	</template>
	//把创建的模板注册到Vue中 这里使用上边定义的id选择器注册
	<script>
	Vue.component("third-component", {
		template: "#third";
	})
	</script>
</body>

接下来我们看下使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" ,content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js '></script>
</head>

<body>
    <div id="app">
        <first-component></first-component>
        <second-component></second-component>
        <third-component></third-component>
        <four-component></four-component>
    </div>
    
    <!-- 第三种 注册全局组件 用template元素标签创建组件模板 -->
    <template id="third">
        <div>
            <h3>这是我的第三个自定义组件</h3>
        </div>
    </template>

    <script>
        //第一种创建组件的方式 用一个变量接收extend创建的组件
        var com = Vue.extend({
            template: "<h3>这是我的第一个组件</h3>"
        })
        // 然后把创建好的组件放入到Vue中
        Vue.component("first-component", com)

        // 第二种 注册全局组件 注意组件必须在vue控制的元素中使用 直接使用字面量
        Vue.component("second-component", {
            // 创建模板
            template: "<h3>这是我的第二个组件</h3>"
        })

        //第三种 把用js创建的模板注册到Vue的组件中
        Vue.component("third-component", {
            template: "#third"
        })

        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            components() {
            	//定义一个私有的组件,这个组件只能在当前Vue控制的app中使用,除了这个模块就不能使用了
				"four-component": {
					template: "<h4>这是我的第四个组件,但是是私有的</h4>"
				}
            }
        })
    </script>
</body>

</html>

注意点一: 模板的命名:我们可以使用驼峰命名法或者kebab-case (短横线分隔命名) ,但是我们需要注意,在使用的组件的时候,驼峰命名法是不能使用的。所以我们需要把驼峰命名的组件名转换为kebab-case。接下来举个例子:如果我们使用驼峰命名一个组件为myFirstComponent,那么我们使用的时候 <my-first-component> </my-first-component>
注意点二: 组件的模板必须包含在一个根标签中,也就是说模板最外层有且只用一个根标签,如果模板中需要放置多个标签,那么这些标签必须被包含在一个根标签中。例如

template:"<div><h3>这是一个标题</h3><p>这是一个段落</p></div>"

这个模板中有h3和p两个标签,所以我们必须在最外层包含一个div根标签,因为模板最外层有且仅有一个根标签元素。

发布了12 篇原创文章 · 获赞 12 · 访问量 532

猜你喜欢

转载自blog.csdn.net/qq_33463449/article/details/103962437