前言
因為vue2去除了父子組件的雙向數(shù)據(jù)綁定,所以在子組件是不允許修改父組件的屬性的,控制臺會報如下錯誤:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "result" (found in component )
解決辦法
在子組件data中定義一個父組件傳遞過來的副本,再把該副本利用this.$emit("","")給傳回去窟扑,父組件利用自定義事件接受該值
子組件
<template>
<div class="popup-bg" v-bind:class="{active:show}">
<div class="popup">
<div class="info">
{{content}}
</div>
</div>
</div>
</template>
<script type="text/ecmascript-6">
export default{
data(){
return {
timers: [],
show: this.isActive
}
},
props: {
content: {},
isActive: {
type: Boolean
},
},
created(){
},
methods: {
autoClose(){
const t = setTimeout(() => {
this.show = false;
}, 1000);
this.timers.push(t)
}
},
watch: {
isActive: function (val) {
//清空一下timers
if(this.timers){
this.timers.forEach(timer=>{
window.clearTimeout(timer);
})
}
this.show = val
this.timers = [];
this.autoClose();
},
show:function (val) {
this.$emit("on-result-change",val);//發(fā)送副本給父組件
}
}
}
</script>
父組件
<template>
<div class="index">
<v-header :isActive="false" :title="title"></v-header>
<div class="content">
<button @click="show_">點擊</button>
<recruit-info></recruit-info>
</div>
<div class="footer">
<v-footer></v-footer>
</div>
<popup :content="content" :isActive="show" @on-result-change="onResultChange"> </popup>
</div>
</template>
<script type="text/ecmascript-6">
import header from '../../component/header/header.vue';
import footer from '../../component/footer/footer.vue';
import recruitInfo from '../../component/recruit-info/recruit-info.vue'
import popup from '../../component/popup/popup.vue'
export default{
data(){
return {
title: String,
show: Boolean,
content: "",
}
},
created (){
this.title = "拉勾網(wǎng)";
this.show = false
},
components: {
"v-header": header,
"v-footer": footer,
"recruit-info": recruitInfo,
"popup": popup
},
methods: {
show_: function () {
this.content = "hello world";
this.show = true
},
onResultChange(val){//自定義事件接受子組件傳遞過來的參數(shù)
this.show = val
}
}
}
</script>
<style lang="stylus" rel="stylesheet/stylus">
.index
position: relative
height: 100%
.content
overflow: auto
overflow-x: hidden
padding-bottom: 45px
.footer
position: fixed
bottom: 0
height: 45px
width: 100%
</style>
```