目录
1.需求:根据组件外部一个变量的值来确定 组件内部的操作。组件外部可以更改filetime的值,filetime有值时这个界面可以操作,否则不可以操作。
我一想 用computed就可以了呀,动态计算一下filetime不就可以了。于是写了下面的代码。然而我发现: 外面的filetime变了,computed函数竟然不执行!!!
还以为写错了,又加了一个watch,打印看到filetime确实变化了,那么computed为什么不执行呢?
1)代码如下:
- <div>div>
- <script >
- import { defineComponent, watch, computed } from "vue";
- // 患者信息
- import { usePatientStoreWithOut } from "@/store";
- const patientInfo = usePatientStoreWithOut().currentOperaMsg;
- export default defineComponent({
- setup() {
- // 监听 filetime变化
- watch(
- () => patientInfo.filetime,
- (newval, oldval) => {
- console.log("watch filetime", patientInfo.filetime);
- workDisabled.save = !!newval;
- }
- );
- // filetime变化时计算 patientInfo_filetime
- const patientInfo_filetime = computed(() => {
- console.log(
- "computed filetime",
- patientInfo.filetime,
- patientInfo_filetime
- );
- return patientInfo.filetime;
- });
- },
- });
- script>
2)结果:filetime变了,computed里面没有执行

1.看了半天,不知道原因。不是说 computed就是:根据响应式数据来动态把数据处理成想要的值吗?patientInfo是响应式的,也变化了,怎么就不执行computed呢?
决定把patientInfo_filetime在页面上显示一下,看看到底有没有变化。
1)代码
- <div>{{ patientInfo_filetime }}div>
- <script >
- import { defineComponent, watch, computed } from "vue";
- // 患者信息
- import { usePatientStoreWithOut } from "@/store";
- const patientInfo = usePatientStoreWithOut().currentOperaMsg;
- export default defineComponent({
- setup() {
- // 监听 filetime变化
- watch(
- () => patientInfo.filetime,
- (newval, oldval) => {
- console.log("watch filetime", patientInfo.filetime);
- workDisabled.save = !!newval;
- }
- );
- // filetime变化时计算 patientInfo_filetime
- const patientInfo_filetime = computed(() => {
- console.log(
- "computed filetime",
- patientInfo.filetime,
- patientInfo_filetime
- );
- return patientInfo.filetime;
- });
- },
- });
- script>
2)结果:太神奇了,patientInfo_filetime确实变化了,computed函数竟然也执行了!!!
真是不可思议!!!

2.经测试发现:computed是不会主动触发的,即使computed依赖的响应式数据变化了。
只有在中或 函数中 使用 computed属性,computed属性的计算方法才会执行。
如果你不使用计算属性,即使真的变化了,也不会计算!!!
3.解决方法
1)watch监听到filetime时进行逻辑处理
2)用computed不可行,因为我外部filetime的变化,并不会触发这个页面的函数,我不能在函数中使用computed属性;在页面的template中也确实不需要使用 computed计算出来的属性
1.computed方法不被调用的原因:
1)computed计算方法写的有问题:检查一下代码是否正确
2)watch监听一下,如果有变化;但是computed没有执行,则很有可能是 没有使用computed计算属性。
2.watch和computed
1)发现他们的一个区别是:watch监听到变化就执行:computed只有在你使用 computed计算属性时computed方法才会被调用。要根据不同场景判断到底要使用哪个!!!
2)一般在 中有用到computed计算属性时,才使用computed;其余情况使用watch监听。
/*
希望对你有帮助!
如有错误,欢迎指正,非常感谢!
*/