1. 程式人生 > >vue.js父子元件

vue.js父子元件

父子元件:

1. 父子元件間的作用域相互獨立。

2. 子元件只能在父元件的配置項裡建立。

3. 子元件只能在父元件的模板中進行呼叫。

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<title>Document</title>
	<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
	<div id="div">
		<parent></parent>
		<son></son>
	</div>
	
	<template id="parent">
		<div>
			<p>{{ msg }}{{ msg2 }}</p>
			<!--呼叫子元件-->
			<son></son>
		</div>
		
	</template>
	
	<template id="son">
		<p>{{ msg2 }}{{ msg }}</p>
	</template>
</body>
</html>
<script type="text/javascript">
	var vm = new Vue({
		el: '#div',
		components:{
			'parent':{
				template:'#parent',
				data:function(){
					return{
						'msg':'haha'
					}
				},				
//				建立子元件
				components:{
					'son':{
						template:'#son',
						data:function(){
							return{
								'msg2':'hehe'
							}
						}
					}
				}
			}
			
		}
	})
</script>