vue组件间的传值方式及方法调用汇总

1.传值

a.父组件传子组件(个人偏向方法一)

方法一:

父页面:

<myReportContent v-if="contentState==1"  :paramsProps='paramsProps'   @back="back" :reportId="reportId" :reportTypex="reportTypex"></myReportContent>
  
import myReportContent from './myReportContent.vue'
 
components: {
  myReportContent
}

子页面:

    props: {
      reportTypex: {
        type: String
      },
      reportId: {
        type: String
      },
      paramsProps:{
        type:Object,
        default:{}
      }
    },

 方法二:

父组件

  provide:{
    nameGet: 'ab888'
  },

子组件

  inject:['nameGet'],
  data () {
    return {
      msg: 'componentA',
      amount: 1,
      name: this.nameGet
    }
  },

  b.子组件传父组件

方法一:(也是子组件调用父组件方法的案例)

父组件

<componentb @backParent='backParent'></componentb>

import componentb from 'components/componentB'

components: {
      componentb
}

backParent(amount){
      console.log('获取子组件传过来的数量:' + amount)
}  

子组件

    changeDataMsg(){
      this.$emit('backParent',this.amount)
      // this.$router.push({path:'/'})
    }

2.方法调用

a.父组件调用组件方法

 方法一:

    <h1>{{nameG}}<button @click="parentF">父组件按钮</button></h1>
    <componenta ref="childa"></componenta>

    parentF(){
        this.$refs.childa.changeDataMsg()
    }  

子组件

    changeDataMsg(){
      console.log('父组件调用子组件方法:ref')
    }

 方法二:

b.子组件调用父组件方法

方法一:见1中b的方法一

方法二:

父组件

parentFun(){
      console.log('子组件调用父组件方法:$parent') 
}

子组件

changeDataMsg(){
      this.$parent.parentFun()
 }

方法三:

父组件

    <componentb @backParent='backParent' :parentFuntion="parentFuntion"></componentb>
    parentFuntion(){
      console.log('子组件调用父组件方法:props')
    }

子组件

    changeDataMsg(){
      this.parentFuntion()
    }

猜你喜欢

转载自www.cnblogs.com/cx709452428/p/10616983.html