一.为什么要组件模板抽离
我们作为计算机专业的IT人员,十分注意代码的质量,比如笔者非常赞同雷军写代码要写“诗一样的代码”,我们在上一篇《Vue—主件详解》就通过语法糖简化了我们的注册过程,但是我们通过观察,发现在Vue中写Html代码显然有些臃肿,所以我们想到可以通过模板抽离的方法将我们在Vue中的Html代码或是其他模板分离出来,使得我们的代码更加整洁。
没有使用组件模板分离前的实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<div id = "app">
<!--使用组件-->
<my-button></my-button>
<my-button></my-button>
<my-button></my-button>
</div>
<script type = "text/javascript">
//创建组件构造器
//注册组件
Vue.component('myButton',{
template:
`<h1>
Good Morning
</h1>`
})
const app = new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>
我们共有两种模板分离的写法。
二.使用<script>标签
语法详解:
(1) 使用<script></script>将我们的模板包裹起来,注意type为text/x-template,然后要给模板起一个id,不然我们的主件不能挂载在组件上。
(2)只需将模板与组件联系就好了。
使用<script>标签 的实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<script type = "text/x-template" id = "myTemplate">
`<h1>
Good Morning
</h1>`
</script>
<div id = "app">
<!--使用组件-->
<my-button></my-button>
<my-button></my-button>
<my-button></my-button>
</div>
<script type = "text/javascript">
//创建组件构造器
//注册组件
Vue.component('myButton',{
template:"#myTemplate"
})
const app = new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>
三.使用<template>标签
与<script>标签 差不多,这里就不重复了。
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<template id = "myTemplate">
`<h1>
Good Morning
</h1>`
</template>
<div id = "app">
<!--使用组件-->
<my-button></my-button>
<my-button></my-button>
<my-button></my-button>
</div>
<script type = "text/javascript">
//创建组件构造器
//注册组件
Vue.component('myButton',{
template: "#myTemplate"
})
const app = new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>