方法一:不要给子组件props进行重新赋值,通过子组件操作this.$emit,直接把值传给父组件,再由父组件渲染到子组件先试试
父组件
<div>
<!-- 子组件 -->
<ceshi :datafu.sync="datafu" ></ceshi>
{{datafu}}
<div @click="fuzujian">fuzujian</div>
</div>
<script>
import ceshi from "@/components/ceshi";
export default {
name: "Home",
components: {
ceshi
},
data() {
return {
datafu:1
}
},
methods: {
fuzujian(){
this.datafu=60
},
}
}
</script>
子组件
<template>
<div>
{{datafu}}
<button @click="anniu">按钮</button>
</div>
</template>
<script>
export default {
name: "ceshi",
data(){
return{
}
},
props: ["datafu"],
mounted() {},
methods: {
anniu(){
let that=this
this.$emit("update:datafu", that.datafu+1);
},
}
</script>
方法二:当子组件props进行赋值时,父组件无法控制到被赋值了的子组件中的值,子组件中使用监听事件watch()修改子组件中的值(父组件中多次使用到该子组件,并且显示不同值)
父组件
<div>
<!-- 子组件 -->
<ceshi :datafu.sync="datafu" ></ceshi>
{{datafu}}
<div @click="fuzujian">fuzujian</div>
</div>
<script>
import ceshi from "@/components/ceshi";
export default {
name: "Home",
components: {
ceshi
},
data() {
return {
datafu:1
}
},
methods: {
fuzujian(){
this.datafu=60
},
}
}
</script>
子组件
<template>
<div>
{{datafus}}
<button @click="anniu">按钮</button>
</div>
</template>
<script>
export default {
name: "ceshi",
data(){
return{
datafus:50
}
},
props: ["datafu"],
mounted() {
this.datafus=this.datafu
},
methods: {
anniu(){
let that=this
that.datafus++
this.$emit("update:datafu", that.datafus);
}
},
watch:{
datafu(newdata,olddata){
this.datafus=newdata
}
}
}
</script>
方法三:当子组件props进行赋值时,父组件无法控制到被赋值了的子组件中的值,子组件绑定一个key,重新渲染子组件(不建议)
在子组件绑定一个key,来让vue的diff算法可以比较两次key值是否不同,如果不同,vue就会重新加载子组件,否则就保持原有状态,这样就可以达到目的了,时间戳,随机数都行 父组件
<div>
<!-- 子组件 -->
<ceshi :datafu.sync="datafu" :key="timer" ></ceshi>
{{datafu}}
<div @click="fuzujian">fuzujian</div>
</div>
<script>
import ceshi from "@/components/ceshi";
export default {
name: "Home",
components: {
ceshi
},
data() {
return {
datafu:1
}
},
methods: {
fuzujian(){
this.timer = new Date().getTime()
this.datafu=60
},
}
}
</script>
子组件 mounted中进行了赋值
<template>
<div>
<!-- {{datafu}} -->
{{datafus}}
<button @click="anniu">按钮</button>
</div>
</template>
<script>
export default {
name: "ceshi",
data(){
return{
mve:"11",
datafus:""
}
},
props: ["datafu"],
mounted() {
//进行了赋值
this.datafus=this.datafu
},
methods: {
anniu(){
let that=this
this.datafus=this.datafus+1
this.$emit("update:datafu", that.datafus);
}
},
}
</script>
方法四:使用vuex(这里就不显示代码了)