父组件:

<template>
  <div>
    <input type="text" v-model="inpMessage">
    <button @click="handleClick">点击传给子组件</button>
    <children :message="clickData" />  //message为子组件props接收的值,clickData为父组件要传的值
  </div>
</template>

<script>
  import children from './page/children'
  export default {
    name: "index",
    components:{
      children
    },
    data(){
      return{
        inpMessage:'',
        clickData:''
      }
    },
    methods:{
      handleClick(){
        //赋值
        this.clickData = this.inpMessage
      },
    }
  }
</script>

子组件:

<template>
    <div>
      <input type="text" v-model="childrenMessage">
    </div>
</template>

<script>
    export default {
        name: "children",
      props:{
          message:String
      },
      data(){
          return{
            childrenMessage:''
          }
      },
      created(){
        this.childrenMessage=this.message
      },

      //这里用watch方法来监听父组件传过来的值,来实现实时更新
      watch:{
        message(val){    //message即为父组件的值,val参数为值
          this.childrenMessage = val    //将父组件的值赋给childrenMessage 子组件的值
        }
      }

    }
</script>
Logo

前往低代码交流专区

更多推荐