代码如下:
局部组件模式:
<!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的方式向上一层触发事件,父组件监听子组件穿过来的事件,如果传了属性值子组件就会把数据带出来给到父组件。
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦