<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TodoList</title>
</head>
<body>
<div id="app">
<todo-header>
<template v-slot:title>
<h1>TodoList</h1>
</template>
<template #subtitle>
<h3>事情是做不完的!!!</h3>
</template>
</todo-header>
<!-- <todo-input @custom="addTodoItem"></todo-input> -->
<todo-input v-model="inputValue" :value="inputValue" @add="addTodoItem"></todo-input>
<todo-list :todos="todos" @remove="deleteTodoItem"></todo-list>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script>
// 定义头部组件
Vue.component('TodoHeader', {
template: `
<div>
<slot name="title">
<h1>主标题:待办事项列表</h1>
</slot>
<slot name="subtitle">
<h2>副标题:今日事今日毕</h2>
</slot>
</div>
`
})
// 定义输入组件
// Vue.component('TodoInput', {
// template: `
// <div>
// <input type="text" placeholder="请输入新的待办事项" v-model="inputValue" />
// <button @click="addHandler">添加</button>
// </div>
// `,
// data() {
// return {
// inputValue: ''
// }
// },
// methods: {
// addHandler() {
// this.$emit('custom', this.inputValue)
// }
// }
// })
Vue.component('TodoInput', {
template: `
<div>
<input
type="text"
placeholder="请输入新的待办事项"
:value="value"
@input="$emit('input', $event.target.value)"
ref="inputRef"
/>
<button @click="addHandler">添加</button>
</div>
`,
props: ['value'],
methods: {
addHandler() {
this.$emit('add')
// document.querySelector('#todo-input').focus()
// console.log(this.$refs)
this.$refs.inputRef.focus()
}
}
})
// 定义列表项组件选项对象
const todoItemOptions = {
template: `
<li>
<span>标题:{{ title }},状态:{{ completed ? '已完成' : '未完成' }}。</span>
<button>修改状态</button>
<button @click="$emit('delete', id)">删除</button>
</li>
`,
props: ['id', 'title', 'completed']
}
// 定义显示列表组件
Vue.component('TodoList', {
template: `
<div>
<div>所有待办事项</div>
<ul>
<todo-item
v-for="todo in todos"
:key="todo.id"
:id="todo.id"
:title="todo.title"
:completed="todo.completed"
v-bind="todo"
@delete="$emit('remove', $event)"
></todo-item>
</ul>
</div>
`,
components: {
TodoItem: todoItemOptions
},
props: ['todos'] // 表示能够接收名为 'todos' 的属性
})
new Vue({
el: '#app',
data: {
/**
* 保存所有待办事项的数组
*/
todos: Array(10).fill(null).map((v, i) => ({
id: i,
title: '标题' + i,
completed: false
})),
// 从输入框中接收到的输入
inputValue: ''
},
methods: {
/**
* 删除待办事项
*/
deleteTodoItem(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
},
/**
* 添加待办事项
*/
// addTodoItem(title) {
// this.todos.unshift({
// id: Math.random(),
// title,
// completed: false
// })
// }
addTodoItem() {
this.todos.unshift({
id: Math.random(),
title: this.inputValue,
completed: false
})
this.inputValue = ''
}
}
})
</script>
</body>
</html>
转载请注明原文地址:https://ipadbbs.8miu.com/read-45986.html