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><br>
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') <br>}
子组件
changeDataMsg(){
this.$parent.parentFun()
}
方法三:
父组件
<componentb @backParent='backParent' :parentFuntion="parentFuntion"></componentb> parentFuntion(){
console.log('子组件调用父组件方法:props')
}
子组件
changeDataMsg(){
this.parentFuntion()
}
【https://www.cnblogs.com/cx709452428/p/10616983.html】
网友评论