批改状态:合格
老师批语:
即父组件通过属性的方式向子组件传值,子组件通过 props 来接收。
例如我们要把“msg”的内容传给子组件:
let app = new Vue({el:"#app",data(){return{msg:"hello!子组件"}},components:{boyComponent}})
在子组件中用props(固定的)来接收:
const boyComponent={props:["msg"],template:`<div>{{msg}}</div> `,}
我们在组件中绑定并运行:
<div id="app"><boy-component :msg="msg"></boy-component></div>

子组件向父组件传参是通过声明同名事件来实现,$emit(父组件中要使用的方法名称,子组件要传给父组件的值 )
例如:
let boyComponent = {\\固定使用$emit(),参数是:父组件要使用的方法名,和要传给父组件的值template:`<button @click="$emit('child',info)">发送</button>`,data(){return{info:"hello!父组件"}},}
然后在Vue实例中写一个接受函数:
let app=new Vue({el:"#app",components:{boyComponent},methods:{accept:function(info){console.log(info)}}})
调用组件并运行:
<div id="app"><boy-component @child="accept"></boy-component></div>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号