Blogger Information
Blog 37
fans 1
comment 0
visits 32504
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Vue组件之间的传值
Jason Pu?
Original
732 people have browsed it

一、父组件向子组件传值

即父组件通过属性的方式向子组件传值,子组件通过 props 来接收。
例如我们要把“msg”的内容传给子组件:

  1. let app = new Vue({
  2. el:"#app",
  3. data(){
  4. return{
  5. msg:"hello!子组件"
  6. }
  7. },
  8. components:{
  9. boyComponent
  10. }
  11. })

在子组件中用props(固定的)来接收:

  1. const boyComponent={
  2. props:["msg"],
  3. template:`<div>{{msg}}</div> `,
  4. }

我们在组件中绑定并运行:

  1. <div id="app">
  2. <boy-component :msg="msg"></boy-component>
  3. </div>


二、子组件向父组件传值

子组件向父组件传参是通过声明同名事件来实现,$emit(父组件中要使用的方法名称,子组件要传给父组件的值 )
例如:

  1. let boyComponent = {
  2. \\固定使用$emit(),参数是:父组件要使用的方法名,和要传给父组件的值
  3. template:`<button @click="$emit('child',info)">发送</button>`,
  4. data(){
  5. return{
  6. info:"hello!父组件"
  7. }
  8. },
  9. }

然后在Vue实例中写一个接受函数:

  1. let app=new Vue({
  2. el:"#app",
  3. components:{
  4. boyComponent
  5. },
  6. methods:{
  7. accept:function(info){
  8. console.log(info)
  9. }
  10. }
  11. })

调用组件并运行:

  1. <div id="app">
  2. <boy-component @child="accept"></boy-component>
  3. </div>

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post