组件在项目中是经常会用到的,它可以是全局注册的组件以及局部注册的组件,我们分别来看不同的组件
1>全局注册的组件
<!DOCTYPE html>
<
html
lang=
"en">
<
head>
<
meta
charset=
"UTF-8">
<
script
type=
"text/javascript"
src=
"js/vue.js"></
script>
<
title></
title>
</
head>
<
body>
<
div
id=
"app">
<
test></
test>
<
test></
test>
</
div>
<
script
type=
"text/javascript">
//注册全局组件
Vue.
component(
'test',{
template:
'<div>全局注册的组件</div>'
})
var app
=new
Vue({
el:
'#app',
data:{
}
})
</
script>
</
body>
</
html>
需要注意的是1:全局注册的component后面是没有s的;1:它可以多个地方使用它
组件的强大之处是可以和模板联合使用,以一个例子来说明:
<!DOCTYPE html>
<
html
lang=
"en">
<
head>
<
meta
charset=
"UTF-8">
<
script
type=
"text/javascript"
src=
"js/vue.js"></
script>
<
title></
title>
</
head>
<
body>
<
div
id=
"app">
<
test></
test>
<
test></
test>
</
div>
<
template
id=
"template">
<
div>全局注册的组件和模板联合使用</
div>
</
template>
<
script
type=
"text/javascript">
//注册全局组件
Vue.
component(
'test',{
template:
'#template'
})
var app
=new
Vue({
el:
'#app',
data:{
}
})
</
script>
</
body>
</
html>
下面我把上面第三种以代码的形式呈现给大家:
<!DOCTYPE html>
<
html
lang=
"en">
<
head>
<
meta
charset=
"UTF-8">
<
script
type=
"text/javascript"
src=
"/js/vue.js"></
script>
<
title></
title>
</
head>
<
body>
<
div
id=
"app">
<
test></
test>
<
test></
test>
</
div>
<
script
type=
"x-template"
id=
"template">
<div>全局注册的组件和模板联合使用的举例3</div>
</
script>
<
script
type=
"text/javascript">
//注册全局组件
Vue.
component(
'test',{
template:
'#template'
})
var app
=new
Vue({
el:
'#app',
data:{
}
})
</
script>
</
body>
</
html>
<!DOCTYPE html>
<
html
lang=
"en">
<
head>
<
meta
charset=
"UTF-8">
<
script
type=
"text/javascript"
src=
"js/vue.js"></
script>
<
title>component-1</
title>
</
head>
<
body>
<
div
id=
"app">
<
test></
test>
</
div>
<
script
type=
"text/javascript">
var app
=new
Vue({
el:
'#app',
components:{
"test":{
template:
'<div">局部注册的组件</div>'
}
}
})
</
script>
</
body>
需要大家注意的是:1>局部组件相对于全部组件而言,它的位置在vue中,以及components后面必须有s,代表可能是多个组件;2>每一个组件在html中也可以多次使用.更加方便管理.
局部组件和全部组件一样,都可以利用模板的三种不同写法来适用不同的环境.