当前位置: 首页> 教育> 培训 > Vue中子传父通讯实现颜色换行添加删除

Vue中子传父通讯实现颜色换行添加删除

时间:2025/8/5 10:07:19来源:https://blog.csdn.net/m0_72189003/article/details/139769222 浏览次数:0次

如图:列表是写在父组件中,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>

关键字:Vue中子传父通讯实现颜色换行添加删除

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: