vue 父组件给子组件传值,子组件给父组件传值

父组件如何给子组件传值

使用props

举个例子:

子组件:fromTest.vue,父组件 app.vue

fromTest.vue

<template>

<h2>{{title}}</h2>  //title必须是父组件传递的
</template>

<script>

   export default (){

       props:["title"]   //可以是数组,也可以是对象
//如何对title进行校验
//props:{
// type:String,required:true //如果父组件不传值就会报错
//}
} </script>

父组件 app.vue

<template>

<from-test title = "你好 "></from-test>     //1.指定值

//<from-test :title = "titleVar "></from-test>     //2.动态传值  titleVar 是变量
</template>

<script>

 export default (){

      data(){

         titleVar :'你好'   //动态传值就代表数据这里需要定义titleVar
    }

   }

</script>

子组件如何给父组件传值

事件,$emit

子组件

button.vue

<template>
   <button @click='handClick'></button>
</template>
<script>
   export default(){
    methods(){
      handClick(){
         this.$emit(lalala,{message:"heihei"})  //lalala是函数名称,后面是想要传递的值

     }
   }
  }
</script>

父组件

app.vue

<template>
    <k-button @lalala = handClick></k-button>
</template>
<script>
import KButton form './components/KButton'    //自己要记得导入组件,引用组件名称
   export default(){  
      components(){
           KButton
      }
      methods(){
          handClick(obj){
             console.log(obj)   //点击button,控制台就收到值了
          }
       }

  }
</script>

可能有写的不对之处,如有发现,请加以指点,谢谢

猜你喜欢

转载自www.cnblogs.com/quitpoison/p/10707535.html