vue 父向子组件传递数据,子组件向父组件传递数据方式

父组件向子组件传递数据通过props,子组件引入到父组件中,设置一个值等于父组件的数据,通过:bind将数据传到子组件中,子组件中通过props接收父组件的数据,这样就可以使用父组件的数据了,循环组件中的对象或数组,:key="item.index",这样是防止报警告;

子组件通过发射事件$emit();发射事件,父组件监听子组件发射的事件,通过事件监听,定义方法接受子组件传递的相关数据,子组件在发射事件的时候可以传递相关的数据,父组件监听的函数可以接收数据;

父组件代码如下:

<template>
<div id="app">
<input type="text" v-model="inputValue" />
<button @click="handleBtn">提交</button >
<Hello :content="item" :index="index" :key="item.index" v-for="(item ,index) in list"
//监听子组件发射的delete事件,并且绑定handleDelete方法

@delete="handleDelete"></Hello>
    <router-view/>
</div>
</template>
<script>
//子组件引入
import Hello from './components/HelloWorld'
export default {
name: 'App',
components:{
Hello
},
data(){
return {
list:[],
inputValue:'',

}
},
methods:{
handleBtn(){
this.list.push(this.inputValue);
this.inputValue = '';
},
//接收子组件传递的数据
handleDelete(index){

this.list.splice(index,1)
}
}
}
</script>
子组件代码
<template>
<div class="hello">

<ul>
<li @click="handleClick"

>{{content}}</li>
<li></li>
</ul>
</div>
</template>
<script>
export default {
props:['content','index'],
data () {

return {
}
},
methods:{
handleClick(){
//发射事件delete,发射props中的index(这里是list的数组索引)
this.$emit('delete',this.index);
}
}
}

</script>
 

猜你喜欢

转载自www.cnblogs.com/zhx119/p/9476962.html