本文主要是介绍Vue中子传父通讯实现颜色换行添加删除,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如图:列表是写在父组件中,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中子传父通讯实现颜色换行添加删除的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!