手记

通过todo-list案例对父子组件的传递(总结)

代码如下:
局部组件模式:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Todo List</title>
	<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
</head>
<body>
	<div id="root">
		<div>
			<input type="text" v-model="todoValue">
			<button @click="handleBtnClick">submit</button>
		</div>
		<ul>
			<todo-item :content="item" 
					   :index="index"
					   v-for="(item, index) in list" 
					   @delete="handleItemDelete">
			</todo-item>
		</ul>
	</div>
	<script>
		// 局部组件
		var TodoItem = {
			props: ['content', 'index'],
			template: "<li @click='handleItemClick'>{{ content }}</li>",
			methods: {
				handleItemClick: function(){
					this.$emit('delete', this.index)
				}
			}
		}
		var app = new Vue({
			el: '#root',
			components: {
				TodoItem: TodoItem
			},
			data: {
				todoValue: '',
				list: []
			},
			methods: {
				handleBtnClick: function(){
					this.list.push(this.todoValue)
					this.todoValue = ''
				},
				handleItemDelete: function(index){
					this.list.splice(index, 1)
				}
			}
		})
	</script>
</body>
</html>

全局组件模式:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
</head>
<body>
	<div id="root">
		<div>
			<input type="text" v-model="value">
			<button @click="handleBtnClick">submit</button>
		</div>
		<ul>
			<todo-item :content="item" :index="index" v-for="(item, index) in list" @delete="handleItemDelete"></todo-item>
		</ul>
	</div>
	<script>
		// 全局组件
		Vue.component('TodoItem', {
			props: ['content', 'index'],
			template: "<li @click='handleItemClick'>{{ content }}</li>",
			methods: {
				handleItemClick: function(){
					this.$emit('delete', this.index)
				}
			}
		})
		var app = new Vue({
			el: "#root",
			data: {
				value: '',
				list: []
			},
			methods: {
				handleBtnClick: function(){
					this.list.push(this.value)
					this.value = ''
				},
				handleItemDelete: function(index) {
					this.list.splice(index, 1)
				}
			}
		})
	</script>
</body>
</html>

父组件通过v-bind的绑定方式进行数据的传递,子组件通过props属性接收父组件穿过来数据也就是content与index。
$emit(事件名称, […属性值])。
子组件通过$emit的方式向上一层触发事件,父组件监听子组件穿过来的事件,如果传了属性值子组件就会把数据带出来给到父组件。

0人推荐
随时随地看视频
慕课网APP