全局组件特性
- 全局组件使用时要放在任意已经绑定Vue实例化对象的标签内部才能被渲染
- 如果放在没有绑定Vue对象的区域则无法生效。
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<itembox/>
</div>
<hr>
<div id="app2">
<itembox/>
</div>
<hr>
<itembox/>
</body>
</html>
<script>
Vue.component("itembox",{
template:`
<div>
<h1>冒险岛</h1>
<p>恶魔猎手</p>
</div>
`
})
new Vue({
el:"#app",
data:{
},
methods:{
}
})
new Vue({
el:"#app2"
})
</script>
- 19-26行新建了一个全局组件itembox
- 第12行在已经绑定Vue对象的
<div id="app">
标签内添加<itembox>
- 第16行在已经绑定Vue对象的
<div id="app2">
标签内添加<itembox>
- 第19行直接在未绑定对象的标签区域填写
<itembox>
组件名
测试页面:
可以发现只显示了两次组件,说明未在绑定VUE对象的区域填写全局组件是无效的,全局组件可以在任意绑定了VUE对象的区域生效。
组件代码片段抽离
之前将代码片段封装的时候,当写入`
` 时不会提示,其中的标签都无法提示编写影响效率。
所以可以将代码抽离出来,方法如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<itembox></itembox>
</div>
<template id="myTem">
<div>
<h3>冒险岛</h3>
<h3>maple story</h3>
</div>
</template>
</body>
</html>
<script>
Vue.component("itembox",{
template:`#myTem`
})
new Vue({
el:"#app",
data:{
},
methods:{
}
})
</script>
第一步14-19行
- 添加一个template标签,并且绑定一个id
- 然后新建一个div标签,将所需要封装组件的样式代码添加进去
第二步23-25行
- 新建一个全局组件
- template中绑定id为myTem的template标签
测试页面:
可以发现组件生效,并且组件代码被抽离到了template标签中,可以使用编码提示。
此处评论已关闭