案例效果
对 input 框输入的内容以列表形式展示,并在点击时删除对应的内容
代码实例
<!DOCTYPE html>
<html>
<head>
<title>组件测试</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="demo">
<input v-model="inputValue">
<button @click="handleSubmit">提交</button>
<ul>
<demo-component v-for = "(item, index) of values"
:key = index
:content = item
:index = index
@delete = handleDelete
>
</demo-component>
</ul>
</div>
<script>
// 注册全局组件
Vue.component('demo-component', {
// 接收向组件传递的数据
props: ['index', 'content'],
template: '<li @click = "handleClick">{{content}}</li>',
methods: {
handleClick: function () {
// 调用外层的‘delete’事件
this.$emit('delete', this.index);
}
}
});
new Vue({
el: '#demo',
data: {
inputValue: '',
values: []
},
methods: {
handleSubmit: function () {
if (this.inputValue != '') {
this.values.push(this.inputValue);
this.inputValue = '';
}
},
handleDelete: function (index) {
this.values.splice(index, 1);
}
}
})
</script>
</body>
</html>