Vue.js 父组件给子组件传值

父组件给子组件传值

  1. 父组件调用子组件的时候,绑定动态属性

<headerchild :title="title" :run="run" :header="this"></headerchild>

2.在子组件里面通过props接收父组件传过来的数据
props:[‘title’]

props:{‘title’:String} /验证父组件传过来的数据/

3.直接在子组件里面使用

//父组件
<template>
  <div id="header">  
    <headerchild :title="title" :run="run" :home="this"></headerchild>
  </div>
</template>
<script>
import HeaderChild from './HeaderChild'
export default {
  data () {
      return {
          title:'我是父组件传过来的。'
      }
  },
  methods: {
     run:function(){
         alert("我是父组件里面的方法");
     }
  },
  components: {
      'headerchild': HeaderChild
  }
}
</script>
<style lang="sass" scoped>

</style>


//子组件
<template>
  <div id="headerchild">
      我是子组件----{{title}}
      <button @click="run">执行父组件的方法</button>
      <button @click="getParent()">获取父组件的数据和方法</button>
  </div>
</template>
<script>
export default {
  data () {
      return {}
  },
  methods:{
      getParent(){
          alert(this.home) /*获取整个父组件*/
          alert(this.home.title) /*获取父组件的数据*/
          alert(this.home.run) /*获取父组件的方法*/
      }
  },
  props:['title','run','home'] /*通过props接收父组件传递过来的数据 */
}
</script>


猜你喜欢

转载自blog.csdn.net/zhongshijun521/article/details/80610308