vue组件

组件的全局注册:
注册的标准写法:

var Hello = Vue.extend({
	template: '
hello component
'
}) Vue.component('Hello',Hello)

简写:

Vue.component(组件名称, 组件的配置项)

Html:
<div id="app">
	<Hello></Hello>
	<Hello/>
</div>

Js:
Vue.component('Hello',{
	template: '

Hello 全局注册

'
, computed: { }, methods: { }, watch: { } }) new Vue({ el: '#app' })

组件的局部注册:

Html:
<div id="app">
	<hello-yyb></hello-yyb>
	<hello-yyb/>
</div>

Js:
new Vue({
	el: '#app',
	components: {
		'hello-yyb': {
			template: '
hello 张三今天干吗去了
'
} } })

组件嵌套的全局注册形式:

Html:
<div id="app">
	<Father></Father>
</div>

Js:
/* 



上面写法是错的 why? 组件的渲染内容是由配置项 template决定的
 
正确写法: 
将子组件以标签的形式放在父组件的tempalte选项中,如下所示
*/
Vue.component('Father',{
	template: '

father

'
}); Vue.component('Son',{ template: '

son

'
}); new Vue({ el: '#app', })

组件嵌套的局部注册形式:

Html:
<div id="app">
	<Father></Father>
</div>

Js:
/* 
组件嵌套: 局部注册形式
子组件必须在父组件中注册之后才能在父组件的模板中使用
*/
new Vue({
	el: '#app',
	components: {
		'Father': {
			template: '
father
'
, components: { 'Son': { template: '

Son

'
} } } } })

template外用

Html:
<div id="app">
  <Hello></Hello>
</div>
<template id="Hello">
  <div class="content">
    <ul>
      <li><a href="">你好</a></li>
      <li><a href="">你好</a></li>
      <li><a href="">你好</a></li>
    </ul>
  </div>
</template>

Js:
Vue.component('Hello',{
	template: '#Hello'
})
new Vue({
	el: '#app',
})

组件模板的根元素唯一

总结:

组件的template如果body里面的话,一定记住要放在 #app 的div外
组件的template在body中使用的话, 是不会解析的, 但是组件内的template是会解析的
组件的模板中的直接子元素必须有一个, 如果你要有多个, 必须使用v-if v-else-if
组件中data选项
根实例中的data选项是一个对象, 但是组件中的data选项是一个函数, why?

函数的作用:

函数有独立作用域
函数可以有return 返回值 , 组件的data选项必须有return 返回值, 并且返回值是一个对象,组件的数据在组件的模板中使用

Html:
	<div id="app">
		<Hello/>
	</div>
	<template id="Hello">
		<div>
			{{ msg }}
		</div>
	</template>
	 
Js:
	Vue.component('Hello',{
		template: '#Hello',
		data(){
			return {
				msg: 'hello 骏哥'
			}
		}
	})
	new Vue({
		el: '#app',
		data: {}
	})
	```

你可能感兴趣的:(5年前端开发)