组件是为了更好的管理、维护代码
定义全局组件
Vue.component("TodoItem", {
props: ['content'],
template: "<li>{{content}}</li>"
});
定义局部组件
// 局部组件
var TodoItem = {
props: ['content'],
template: "<li>{{content}}</li>"
}
var app = new Vue({
el: '#app',
components: {
TodoItem: TodoItem // 绑定局部组件
},
data: {
list: [],
inputValue: ''
},
methods: {
handleClick: function () {
this.list.push(this.inputValue);
this.inputValue = '';
}
}
});
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button @click="handleClick">提交</button>
<ul>
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
// 全局的组件
/*Vue.component("TodoItem", {
props: ['content'],
template: "<li>{{content}}</li>"
});*/
// 局部组件
var TodoItem = {
props: ['content'],
template: "<li>{{content}}</li>"
}
var app = new Vue({
el: '#app',
components: {
TodoItem: TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
handleClick: function () {
this.list.push(this.inputValue);
this.inputValue = '';
}
}
});
</script>
</body>
</html>