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

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

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

父组件向子组件传值,是通过属性的方式传值,vue单向数据流,子组件使用父组件的数据,但是不能修改父组件传个子组件的内容,否则会影响其他子组件对父组件的数据引用,因此vue是单向数据流是这么考虑的

父组件代码如下:

<template>
<div ></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>