vue自定义组件(局部和全局)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>组件</title>
	<script src="https://cdn.bootcss.com/vue/2.6.6/vue.js"></script>
	<style>
		.wrap{
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.wrap select{
			background-color: #ccc;
		}
		.wrap select option{
			background-color: orange;
		}
	</style>
</head>
<body>
<div id="app">
	<custom-select></custom-select>
	<custom-select></custom-select>
</div>
<div id="wrap">
	<custom-select></custom-select>
	<custom-select></custom-select>
</div>
<script>
	//注册组件,使用Vue.component是全局注册,使用局部注册不使用Vue.component,直接在new Vue({})中加入components即可,但只能在所在vue对象中使用,超过范围会出错
	Vue.component("customSelect",{
		template:`
		<section class="wrap">
			<h2>我是组件app标题</h2>
			<select>
				<option value="">上海</option>
				<option value="">北京</option>
				<option value="">月球</option>
				<option value="">金星</option>
				<option value="">hello</option>
				<option value="">world</option>
				<option value="">how are you</option>
			</select>
		</section>
		`	
	}),
	new Vue({
		el:"#app"
	}),
	new Vue({
		el:"#wrap",
		components:{
			"customSelect":{
				template:`
				<section class="wrap">
					<h2>我是组件wrap标题</h2>
					<select>
						<option value="">上海</option>
						<option value="">北京</option>
						<option value="">月球</option>
						<option value="">金星</option>
						<option value="">hello</option>
						<option value="">world</option>
						<option value="">how are you</option>
					</select>
				</section>
				`	
			}
		}
	})
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zhangqling/article/details/88537433