在vue2中props只能单向传递数据,及从父组件传递给子组件,但是子组件不能改变父组件传递过来的值,一开始不知道有这个问题的存在,效果能出来,但是项目报错,如下
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.
然后参考https://www.cnblogs.com/xxcanghai/p/6124699.html该文章解决了问题
父组件
<template>
<div id="combat">
<!-- 倒计时组件 -->
<div class="fr" >
<my-clock :time.sync="activity_time" @on-result-change="onResultChange"/>// 注意
</div>
</div>
</template>
< script>
export default {
data(){
return:{
activity_time:null // 注意
}
},
method:{
onResultChange(val){ // 注意
this.time=val;//外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
},
// 获取剩余时间
getDate(endTime){
const newendTime = Date.parse(endTime)
const newData = Date.parse(new Date())
let syTime = (newendTime-newData)/1000
this.activity_time = syTime
console.log(this.activity_time)
}
}
}
</script>
子组件
<template>
<div id="clock_box">
<span class="clock_ico">
<i class="iconfont icon-icon-test"/>
</span>
<time v-text="now_time"/>
</div>
</template>
<script>
export default {
props: {
time: { // 注意
type: Number,
default: null
}
},
data: function() {
return {
now_time: '',
son_time: this.time// 注意
}
},
created() {
this.now_time = this.formatSeconds(this.time)
console.log(this.time)
},
mounted() {
var that = this
var timer = setInterval(function() {
that.son_time--
if (that.son_time <= 0) {
clearInterval(timer)
}
that.now_time = that.formatSeconds(that.son_time)
}, 1000)
},
watch: {// 注意
time(val) {
this.son_time = val;//新增result的watch,监听变更并同步到myResult上
},
son_time(val){
this.$emit("on-result-change",val);//③组件内对myResult变更后向外部发送事件通知
}
},
methods: {
formatSeconds(s) {
var t
if (s > -1) {
var hour = Math.floor(s / 3600)
var min = Math.floor(s / 60) % 60
var sec = s % 60
if (hour < 10) {
t = '0' + hour + ':'
} else {
t = hour + ':'
}
if (min < 10) {
t += '0'
}
t += min + ':'
if (sec < 10) {
t += '0'
}
t += sec
}
return t
}
}
}
</script>