如图:列表是写在父组件中,input框和按钮是写在子组件中的
按照以上示例图有这两个文件
父组件中:AboutView.vue
<template>
<div class="about">
<!-- <h1>This is an about page</h1> -->
<!-- <ul v-for="(item,index) in arr" :key="index">
<li :class="index%2==0?'box':''">{{item}}</li>
</ul>
<hr> -->
<ul>
<li v-for="(item,index) in arr" :key="index">
<span v-color="index">{{item}}</span>
<button @click="shanchu(index)">删除</button>
</li>
</ul>
<!-- 组件之间进行添加 -->
<HelloWorld @fuzujian ="name">
</HelloWorld>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
components: {
HelloWorld
},
data() {
return {
arr:[11,22,33,44,55,66],
}
},
directives:{
color(el,binding){
if(binding.value%2 == 0){
el.style.color = 'red';
}else{
el.style.color = 'green';
}
el.addEventListener('mouseenter',()=>{
el.style.color = 'yellow';
})
el.addEventListener('mouseleave',()=>{
if(binding.value%2 == 0){
el.style.color = 'red';
}else{
el.style.color = 'green';
}
})
}
} ,
methods: {
// 组件之间进行添加
name(a){
// console.log(a);
this.arr.push(a)
},
shanchu(index){
if (confirm("确定要删除吗") == true) {
this.arr.splice(index,1)
} else {
return false;
}
}
}
}
</script>
<style scoped>
ul li{
list-style: none;
}
.box{
color: red;
}
</style>
子组件中components下的HelloWorld.vue
<template>
<div class="hello">
<ul>
<li v-for="(item,index) in arrList" :key="index">
{{item}}
</li>
</ul>
<input type="text" v-model="ipt1"><button @click="tianjia">添加</button>
</div>
</template>
<script>
export default {
data() {
return {
mag:'',
ipt1:'',
arrList:[]
}
},
methods:{
tianjia(){
// 这个是没用组件之间的传参写的添加
// this.arrList.push(this.ipt1);
// console.log(this.ipt1);
// 这个是用组件之间的传参写的添加
this.$emit('fuzujian',this.ipt1)
},
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
ul li{
list-style: none;
}
</style>