vue使用中的父子元件之間傳參的方法
阿新 • • 發佈:2019-02-11
1.父元件傳參到子元件中
父元件中的用法:
1引入元件
import selfAbility from './children/selfAbility';
2.在元件中申明:
components: {
selfAbility
},
3.頁面中使用
<selfAbility :score="scoreParent"></selfAbility>
其中score是與子頁面中的 變數名對應上,scoreParent是父頁面的 資料
子元件中用法:
1.在script中宣告一下
props: {
score: {
type:Object
}
}
2.在初始化渲染的方法中就獲取到此 score的值
created() {
this.initLineScore();
}
在這個方法中可以獲取到score從父頁面傳過來的值
二.從父元件獲取子元件中的資料
子頁面中的寫法:
<el-col :span="24" class="title textCenter">
自身耐蝕能力得分:<el-input v-model="resultScore" placeholder="請輸入分數" @change="scoreSave"></el-input> 分
</el-col>
在方法scoreSave中用$emit方法
scoreSave() {
this .scoreData.evaluatScore = this.resultScore;
this.scoreData.evaluatConfigInfo = {
technicalStandard: {
score: this.firstLineScore,
type: this.radio1
},
meetDemand: {
score: this.secondLineScore,
type: this.radio2
},
partialFailure: {
score: this .thirdLineScore,
type: this.radio3
},
reasonable: {
score: this.resultScore,
type: this.radio4
},
total:this.resultScore
}
this.$emit('childFun', this.scoreData);此時這句如果input沒有改變的時候,基本不執行,需要在 created中再去執行一遍
但是當修改input中的值也是獲取不到,還 不知道為啥
}
created() {
this.initLineScore();
this.$emit('childFun', this.scoreData);
},
***updated()
{
this.$emit('childFun', this.scoreData);
}***
而且當在子元件中修改了scoreData的值也是渲染不出來,只是初始化的時候能獲得到這個初始化的值
子頁面中的程式碼
<selfAbility v-on:childFun="changeScore"></selfAbility>
<el-button type="primary" class="button-medium" @click="saveScore">儲存</el-button>
saveScore(row) {
console.log(this.a);
},
changeScore(data) {
this.a = data;
}
因為子元件中的scoreData 會根據使用者的資料改變,需要在父元件中去實時獲取這個值,所以需要在子元件中更新這個值 用updated更新