为了账号安全,请及时绑定邮箱和手机立即绑定

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

2019.11.25 17:53 3761浏览

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

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Todo List</title>
	<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="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 class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="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下载
官方微信

举报

0/150
提交
取消