VUEX 使用 Computed mapGetters 更新数据模型

VUEX Update data model with Computed mapGetters

我是 Vuex 的新手,每次更新计算的 getter 时,我都会尝试从数据模型更新 card.imageURL 属性。

getter 正在更新,因为我可以观察到组件 HTML 的变化。我只是无法使用此事件来更新数据模型。

我尝试使用 mounted() 方法执行此操作,但未执行下面显示的 if 语句。

有什么建议吗?

谢谢!

<script>
import { mapGetters, mapState } from "vuex";
export default {  
  created() {
    // do some initial fetch
  },
  data() {
    return {
      card: {
        title: "",
        cost: 0,
        description: "",
        imageURL: "",
      },
    };
  },
  mounted(){
    if(this.rewardsImageUrl){
      this.card.imageURL = this.rewardsImageUrl;
      console.log(`set imageURL to card data model: ${this.card.imageURL}`);
    }
  },    
  computed: {
    ...mapState(["user", "setUploadedImageUrl"]),
    ...mapGetters(['rewardsImageUrl'])
  },
  methods: {
    close() {
      this.$emit("close");
    },
    async addCard() {
      this.$emit("close");
    },

    selectImage() {
      this.$refs.selectImage.click();
    },

    async previewImage(event) {
      this.imageFile = event.target.files[0];
      this.$store.dispatch("uploadRewardsImage", this.imageFile);
    },
  },
};
</script>

要收听更改,您可以像这样使用 watch

  computed: {
    ...mapState(["user", "setUploadedImageUrl"]),
    ...mapGetters(['rewardsImageUrl'])
  },
  watch:{
      setUploadedImageUrl(){
        console.log('setUploadedImageUrl changed', this.setUploadedImageUrl)
      },
  },