<template>
<div class="hello">
<span>{{ msg }}</span>
<div></div>
<span>{{ num }}</span>
<button @click="add">+</button>
<span>{{ plusOne }}</span>
</div>
</template>
<script>
import { ref, watch, computed } from "vue";
export default {
name: "HelloWorld",
props: {
msg: {
type: String,
default: () => "默认值",
},
},
setup(props) {
const num = ref(0);
const count = ref(1);
watch(
() => props.msg,//需要监听的信息
(count, prevCount) => {
console.log(count);//新值
console.log(prevCount);//旧值
}
);
function add() {
num.value += 1;
}
const plusOne = computed({//返回一个 ref 对象。
get: () => count.value + 1,//return返回的标准值
set: (val) => {
count.value = val - 1;
},
});
plusOne.value = 1;//开启计算
console.log(count.value); // 0
return {
num,
add,
plusOne,//1
};
},
};
</script>
<style scoped lang="less">
</style>
vue3.0——watch(监听属性)、computed(计算属性)和父传子通信
最新推荐文章于 2024-07-04 16:34:18 发布