父组件
<div id="app">
<child :listitem="list" @changeparent="changeparent"></child>
</div>
** 注册子组件 **
Vue.component('child', { template:
`
<div>
<ul>
<li v-for="(item,index) in listitem" @click="change(index)" :style="{background:item.num==index?'red':''}" :class="{sty:true}">
{{item.name}}
</li>
</ul>
</div>
`,
props: ['listitem'],
methods: {
change(index) {
this.$emit('changeparent', index)
}
},
})
new出来的vue对象
new Vue({ el: '#app', data: { list: [{ name: '苹果手机' }, { name: '小米手机' }, { name: '华为手机' }, { name: 'vivo手机' }] }, methods: { changeparent(index) { console.log(index); // this.list.splice(index, 1) this.list.forEach(r => { r.num = null }); this.$set(this.list, index, { name: this.list[index].name, num: index }) } } })
通过父给子传值 子修改父的data 最后实现给元素添加样式或者删除元素的功能
点击添加背景颜色/删除这一行