一、父组件向子组件传值
方法一:通过props传值
1.创建子组件,在src/components/文件夹下新建一个child.vue
2.在child.vue 中创建props,然后新加一个title属性
<template>
<div>
<h1>child子组件</h1>
<div>{{title}}</div>
</div>
</template>
<script>
export default { name: 'child', props:["title"],}
</script><style scoped lang="less">
</style>
3.在parent.vue父组件中注册child组件,并在template中加入child标签,标签中绑定title属性,并在data中赋值
<template>
<div>
<h1>parent父组件</h1>
<child v-bind:title="parentTitle"></child>
</div>
</template>
<script>import child from './child';//引用子组件export default { name: 'parent', data(){ return
{ parentTitle:"hello,child" }
}, components:{ child }}
</script>
<style scoped lang="less"></style>
父组件向子组件传值总结:
子组件在props中创建一个属性,用以接收父组件传过来的值
父组件中注册子组件
在子组件标签中添加子组件props中创建的属性
把需要传给子组件的值赋给该属性
方法二:通过ref属性,父组件调用子组件的方法,把要传的值作为参数传给子组件,子组件获取该参数,并使用
子组件代码
<template>
<div>
<h1>child子组件</h1>
<div>{{num}}</div>
</div>
</template>
<script>
export default { name: 'child', props:["title"],
data(){ return { isshow:true, num:0, }
}, methods:{ getVal(val){ this.num = val; }
}}
</script>
<style scoped lang="less">
</style>
父组件代码
<template>
<div>
<h1>parent父组件</h1>
<child ref="childnode">
</child>
</div>
</template>
<script>import child from './child';//引用子组件export default {
name: 'parent', data()
{ return {
num:100
}
}, components:{
child },
mounted(){
this.init();
},
methods:{
init(){
//获取子组件属性
this.isshow = this.$refs.childnode.isshow;
console.log("isshow:"+this.isshow);
//父组件调用子组件方法,传值给子组件 this.$refs.childnode.getVal(this.num);
}, }}</script><style scoped lang="less">
</style>
二、子组件向父组件传值
1.在子组件中创建一个按钮,给按钮绑定一个点击事件
2.在响应该点击事件的函数中使用$emit
来触发一个自定义事件,并传递一个参数
<template>
<div>
<h1>child子组件</h1>
<button @click="sendMsgToParent">向父组件传值</button>
</div>
</template>
<script>export default {
name: 'child', methods:{
sendMsgToParent(){ this.$emit("listenToChildEvent","this message is from child")
}
}}
</script>
<style scoped lang="less"></style>
3.在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法
<template>
<div>
<h1>parent父组件</h1>
<child v-on:listenToChildEvent="showMsgFromChild"></child>
</div></template><script>import child from './child';//引用子组件export default {
name: 'parent', data(){
},
components:{ child
}, methods:{
showMsgFromChild(msg)
{ console.log(msg) }
}
}
</script>
<style scoped lang="less"></style>
子组件向父组件传值总结:
子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
将需要传的值作为
$emit
的第二个参数,该值将作为实参传给响应自定义事件的方法在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
总之,在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性或者借助子组件的ref属性。