在不使用vuex的情况下,如何监听呢?
父组件:
<template>
<div class="home">
<child :status="status"></child>
<button @click="changestatus">改变状态</button>
</div>
</template>
<script>
// @ is an alias to /src
import child from '../components/child.vue'
export default {
data() {
return {
status: false
}
},
name: 'home',
components: {
child
},
methods: {
changestatus() {
// console.log(this.status)
this.status = !this.status
console.log(this.status)
}
}
}
</script>
子组件(用计算属性监听)
<template>
<div>
<button>{{switchStatus}}</button>
</div>
</template>
<script>
export default {
props: {
status: {
type: Boolean,
default () {
return false
}
}
},
computed: {
switchStatus: function () {
return this.status
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
<button>{{mystatus}}</button>
</div>
</template>
<script>
export default {
props: {
status: {
type: Boolean,
default() {
return false
}
}
},
data() {
return {
mystatus: false
}
},
watch: {
status (newV, oldV) { // watch监听props里status的变化,然后执行操作
this.mystatus = newV
return this.mystatus
}
}
}
</script>
<style scoped>
</style>
效果和计算属性监听相同
再有总结会再补充