vue 组件间传值

83 阅读1分钟

父组件parent.vue

<template>
  <div class=''>
    父组件
    <child-com ref="childCom" fromParent="我是父组件的值"></child-com>
  </div>
</template>
<script>
import childCom from '@/components/childCom.vue'
export default {
  components: { childCom },
}
</script>

子组件childCom.vue

<template>
  <div>
    子组件
    <div>来自父组件的值fromParent:{{fromParent}}</div>
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    fromParent: {
      type: String,
      default: ""
    }
  },
}

父组件传递到子组件

子组件

props: {
    fromParent: {
      type: String,
      default: ""
    }
  },

父组件

<child-com ref="childCom" fromParent="我是父组件的值"></child-com>
//或者
this.$refs.childCom.childVal = "我是父组件的值";//赋值给子组件 非prop值
this.$refs.childCom.childMT();//调用子组件方法

子组件传递到父组件

子组件

this.$emit("setParentVal","childToParent");
//或者
 this.$parent.parentVal = "childToParent";//赋值给父组件
 this.$parent.parentMT();//调用父组件方法

父组件

//$emit方式
<child-com ref="childCom" @setParentVal="getValFromChild"></child-com> 
getValFromChild(val){
  console.log(val);//childToParent 
}