开发TodoList(v-for,v-on,v-model)
当在输入框中输入字符以后会显示在页面上并清空原输入框内容。
v-on:点击事件 v-model:双向绑定 v-for:循环取数据
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TodoList</title>
<script src='./vue.js'></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue" />
<button v-on:click="handleBtnClick">提交</button>
<ul>
<li v-for="item in list">{{item}}</li>
</ul>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
list: [],
inputValue: ''
},
methods: {
handleBtnClick: function() {
this.list.push(this.inputValue)
this.inputValue = ''
}
}
})
</script>
</body>
</html>
效果图:
![](https://img.haomeiwen.com/i4237161/8cba318593e09734.png)
使用組件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TodoList</title>
<script src='./vue.js'></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue" />
<button v-on:click="handleBtnClick">提交</button>
<ul>
<!-- <li v-for="item in list">{{item}}</li> -->
<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: {
handleBtnClick: function() {
this.list.push(this.inputValue)
this.inputValue = ''
}
}
})
</script>
</body>
</html>
子父组件传值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TodoList</title>
<script src='./vue.js'></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue" />
<button v-on:click="handleBtnClick">提交</button>
<ul>
<!-- <li v-for="item in list">{{item}}</li> -->
<todo-item v-bind:content="item" v-bind:index="index" v-for="(item,index) in list" @delete="handleItemDelete">
</todo-item>
</ul>
</div>
<script>
//全局组件
// Vue.component("TodoItem", {
// props: ['content'],
// template: "<li>{{content}}</li>"
// })
//局部组件
var TodoItem = {
props: ['content', 'index'],
template: "<li @click='handleItemClick'>{{content}}</li>",
methods: {
handleItemClick: function() {
this.$emit("delete", this.index);//子组件向父组件传值
}
}
}
var app = new Vue({
el: '#app',
components: { //注册局部组件
TodoItem: TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
handleBtnClick: function() {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleItemDelete: function(index) {
this.list.splice(index, 1);//執行刪除操作
}
}
})
</script>
</body>
</html>
网友评论