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:'/'}) }
c.兄弟組件之間傳值
方法一(a改變,b也跟着改變-----------------a傳值給b):
創建一個獨立的eventVue.js
import Vue from 'vue' export default new Vue
父組件
<componenta></componenta> <componentb></componentb> import componenta from 'components/componentA' import componentb from 'components/componentB' components: { componenta, componentb },
兄弟組件a
<h1>{{ amount }}</h1>
import eventVue from '@/until/eventVue.js' data () { return { msg: 'componentA', amount: 1 } } changeDataMsg(){ let amount = this.amount + 1 eventVue.$emit('myfun',amount) this.amount = amount }
兄弟組件b
<h1>{{ amount }}</h1>
import eventVue from '@/until/eventVue.js' changeDataMsg(){ eventVue.$on('myfun',(msg)=>{ this.amount = msg }) }
created(){
this.changeDataMsg()
}
方法二(b改變,a也跟着改變-----------------b傳值給a):
父組件
<componenta ref="childa"></componenta> <componentb @backParent='backParent' ></componentb> backParent(number){ this.$refs.childa.changeDataNumber(number) },
兄弟組件b
<button @click="backp">backp</button> <h1>{{ number }}</h1> data () { return { number: 2.1 } }, backp(){ let number = this.number + 1 this.$emit('backParent',number) this.number = number },
兄弟組件a
<h1>{{ number }}</h1> data () { return { number: 9.1, } }, changeDataNumber(number){ this.number = number }
d.父組件的父組件給孫組件傳值(爺爺------>孫子)
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()
}