简介
Vue中的组件定义类似如下效果(当然Vue会更强大):
<ol id="comp">
</ol>
如果要给以上ol标签中添加一个li标签。不使用Vue你会这么做呢? 可能如下是一种方式:
document.getElementById("comp").innerHTML="<li>hello</li>";
以上需求就可以使用Vue的自定义组件解决。但是Vue组件能解决的问题比上面例子要强大和丰富很多。本章节只是介绍Vue组件的基本使用。
Vue组件定义和使用
1、定义一个todo-item组件
Vue.component('todo-item', {
template: '<li>这是个待办项</li>'
})
2、使用todo-item组件
<ol id="comp">
<!-- 创建一个 todo-item 组件的实例 -->
<todo-item></todo-item>
</ol>
3、是组件生效,激活Vue
var app7=new Vue({
el:"#comp",
});
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<ol id="comp">
<!-- 创建一个 todo-item 组件的实例 -->
<todo-item></todo-item>
</ol>
<script type="text/javascript">
Vue.component('todo-item', {
template: '<li>这是个待办项</li>'
})
var app7=new Vue({
el:"#comp",
});
</script>
</body>
</html>
学习前端最好的方式就是动手用一用,效果出来了就明白了。