父组件传值给子组件

只要将子组件注册到父组件里面,然后子组件接收一下父组件的方法就可以了

父组件

<template>
  <div id="app">
    <components-a
      msgFromFather="I am a father"
     ></components-a>
  </div>
</template>

<script>
import ComponentsA from './components/componentsA'
export default {
  components: {ComponentsA},
  data() {
    return{
    }
  },
  methods: {
  }
}
</script>
<style>
</style>

子组件

<template>
  <div class="hello">
      <h1>{{msg}}</h1>
      <button v-on:click="onClickMe">Click!</button>
  </div>
</template>
<script>
export default {
  props:['msgFromFather'],
  data() {
    return {
      msg:'hello from component A'
    }
  },
  methods: {
    onClickMe() {
        console.log(this.msgFromFather);
     }
  }
}
</script>
<style scoped>
</style>

子组件传值给父组件

子组件使用this.$emit发送给父组件,父组件绑定的方法跟子组件发送过来的方法一致即可

父组件

<template>
  <div id="app">
    <components-a
      msgFromFather="I am a father"
      v-on:child-tell-me-something="lisenToMyBoy"
     ></components-a>

     <p>child tell me {{childWords}}</p>
  </div>
</template>

<script>
import ComponentsA from './components/componentsA'

export default {
  components: {ComponentsA},
  data() {
    return{
      childWords:''
    }
  },
  methods: {
    //2.绑定子组件事件 子-父
    lisenToMyBoy(msg){
     // console.log(msg);
     this.childWords=msg
    }
  }
}
</script>

<style>
</style>

注释:

如果子组件传的是一个固定的值,父组件直接写方法就行:child-tell-me-something=”lisenToMyBoy”; 如果子组件传的是一个变量,父组件就要绑定:v-on:child-tell-me-something=”lisenToMyBoy”

子组件

<template>
  <div class="hello">
      <h1>{{msg}}</h1>
      <button v-on:click="onClickMe">Click!</button>
  </div>
</template>

<script>
export default {
  props:['msgFromFather'],
  data() {
    return {
      msg:'hello from component A'
    }
  },
  methods: {
    onClickMe() {
        //2.发送给父级
        this.$emit('child-tell-me-something',this.msg);
        //this.$emit可以传多个参数
        //this.$emit('child-tell-me-something',this.msg,this.msg1,this.msg2);
     }
  }

}
</script>
<style scoped>
</style>

脚注

Vue2.0后 $$dispatch(),$broadcast()被弃用,

demo下载地址:https://github.com/liusi888/vue-value

Logo

前往低代码交流专区

更多推荐