前言
因为vue2去除了父子组件的双向数据绑定,所以在子组件是不允许修改父组件的属性的,控制台会报如下错误:
[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);//发送副本给父组件
}
}
}
</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 = "拉勾网";
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){//自定义事件接受子组件传递过来的参数
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>
```