【发布时间】:2026-01-24 17:40:02
【问题描述】:
根据this post,观察计算属性应该不是问题。然而我的代码却不能正常工作。
<template>
<div v-if="product" class="section">
<form>
<div class="control"><input type="text" class="input" v-model="title"></div>
<div class="control"><input type="text" class="input" v-model="description"></div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
title: null,
description: null
}
},
computed: {
product() {
// const payload = { collection: 'products', id: this.$route.params.productId }
// return this.$store.getters.objectFromId(payload)
console.log('working')
return { title: 'Awesome Title', description: 'Awesome Description' }
}
},
watch: {
product() {
this.title = this.product.title,
this.description = this.product.description
}
}
}
</script>
我希望watch 在product 返回时触发,但它没有。
我可以像这样在计算属性中设置属性:
computed: {
product() {
const payload = { collection: 'products', id: this.$route.params.productId }
const product = this.$store.getters.objectFromId(payload)
this.title = product.title
this.description = product.description
return product
}
}
但是编译器给了我一个警告:error: Unexpected side effect in "product" computed property
【问题讨论】:
-
你想达到什么目的?您的问题可能有更直接的解决方案
-
我已更新我的帖子以更清楚地显示意图。我正在尝试获取产品并设置一些绑定到某些表单输入的初始数据()。我可以在计算函数中设置值,但我在编译器中收到了这个烦人的副作用警告。我认为在 get 中设置属性是不好的做法?
-
您需要设置use a watcher 并设置
immediate才能让您的观察者在初始渲染时触发。 -
@HamishJohnson 您不为此使用计算。看看创建/安装的 vue.js 钩子。在它们内部,您可以加载外部数据并将其附加到当前数据模型
-
@Enrico 是的,我必须同意你的观点——不太清楚为什么我在这种情况下选择了计算。谢谢
标签: javascript vue.js vuejs2 vuex