- props/emit
- props
- 作用:父组件通过 props 向子组件传递数据
- parent.vue
<template> <div> <Son :msg="msg" :pfn="pFn"></Son> </div> </template> <script> import Son from './son' export default { name: 'Parent', data() { return { msg:'a message' } }, methods: { pFn(){ console.log("这是pFn"); } }, components:{ Son } } </script> <style></style>
- son.vue
<template> <div> <h3>p的msg:{{ msg }}</h3> <el-button type="primary" size="default" @click="pfn">点击使用p的方法</el-button> </div> </template> <script> export default { name: 'Son', props:['pfn','msg'] } </script> <style></style>
- 效果
- emit
- 作用:子组件通过 $emit 和父组件通信
- parent.vue
<template> <div> <Son :msg="msg" @onSendData="onSendData"></Son> </div> </template> <script> import Son from './son' export default { name: 'Parent', data() { return { msg:'a message' } }, methods: { }, components:{ Son }, methods: { onSendData(val){ console.log(val); } }, } </script> <style></style>
- son.vue
<template> <div> <h3>p的msg:{{ msg }}</h3> <el-button type="primary" size="default" @click="sendData">点击向p发送数据</el-button> </div> </template> <script> export default { name: 'Son', props:['msg'], created() { console.log(this); }, methods: { sendData(){ this.$emit("onSendData",'data from son') } }, } </script> <style></style>
- 效果
- props
- ref / $refs
- 作用:这个属性用在子组件上,它的用用就指向了子组件的实例,可以通过实例来访问组件的数据和方法
- parent.vue
<template> <div> <Son ref="Son"></Son> </div> </template> <script> import Son from './son.vue'; export default { name: 'Parent', components:{ Son, }, mounted() { console.log("this.$refs.Son",this.$refs.Son.msg); this.$refs.Son.sayHi(); }, } </script> <style></style>
- son.vue
<template> <div> <h3>p的msg:{{ msg }}</h3> </div> </template> <script> export default { name: 'Son', data() { return { msg:"a message from son" } }, methods: { sayHi(){ console.log("hello"); } }, } </script> <style></style>
- 效果