Vue 组合 API 中的只读目标

djc*_*114 13 vue.js vue-reactivity vue-props vuejs3 vue-composition-api

我的“Generateur”组件正在向我的“Visionneuse”组件发送道具。浏览器中一切正常,但我在控制台中看到以下消息:

\n
Set operation on key "texteEnvoye" failed: target is readonly.\n
Run Code Online (Sandbox Code Playgroud)\n

我真的不知道为什么会收到此消息,因为我将道具传递给了引用。\n这是我的组件:\n“Generateur”

\n
<template>\n  <div>\n    <h1>G\xc3\xa9n\xc3\xa9ration d'une carte de voeux</h1>\n    <div class="board">\n      <Visionneuse :texteEnvoye="texte" :taille="0.5"/>\n    </div>\n    <textarea\n      :style="'width: 60%; resize:none;height: 100px;'"\n      v-model="texte"\n      placeholder="\xc3\x89crivez votre texte ici">\n    </textarea>\n  </div>\n  <div>\n    <button\n      v-if="lien.length == 0"\n      id="boutonObtenirLien"\n      v-bind:class="{ enCours: lienEnCours }"\n      class="btn first"\n      @click="obtenirLien">Obtenir le lien</button>\n    <p\n      v-if="lien.length > 0">\n      Votre carte de voeux est accessible au lien suivant:<br/>\n      <a :href="lien">{{ lien }}</a>\n    </p>\n  </div>\n</template>\n\n<script>\nimport Visionneuse from '@/components/Visionneuse.vue';\n\nimport axios from 'axios';\n\nimport {\n  defineComponent, ref,\n} from 'vue';\n\nexport default defineComponent({\n  name: 'G\xc3\xa9n\xc3\xa9rateur',\n  components: {\n    Visionneuse,\n  },\n  setup() {\n    const texte = ref('');\n    const lienEnCours = ref(false);\n    const lien = ref('');\n\n    function obtenirLien() {\n      if (lienEnCours.value) {\n        console.log('Je suis d\xc3\xa9j\xc3\xa0 en train de chercher!');\n        return false;\n      }\n      lienEnCours.value = true;\n\n      axios.post(`${process.env.VUE_APP_API_URL}/textes/creer/`, {\n        texte: texte.value,\n      },\n      {\n        headers: {\n          'Content-Type': 'application/json',\n        },\n      })\n        .then((response) => {\n          console.log(response.data);\n          lien.value = `${process.env.VUE_APP_URL}/carte/${response.data}`;\n        })\n        .catch((error) => {\n          console.log(error);\n        })\n        .then(() => {\n          lienEnCours.value = false;\n        });\n      return true;\n    }\n\n    return {\n      texte,\n      obtenirLien,\n      lienEnCours,\n      lien,\n    };\n  },\n});\n\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

还有“Visionneuse”

\n
<template>\n  <div class="board">\n    <canvas\n      ref='carte'\n      :width="size.w"\n      :height="size.h"\n      tabindex='0'\n      style="border:1px solid #000000;"\n    ></canvas>\n  </div>\n  <div id="texteRemplacement" v-if="petit">\n    <p v-for="p in texte.split('\\n')" v-bind:key="p">\n      {{ p }}\n    </p>\n  </div>\n</template>\n\n<script>\n\nimport {\n  defineComponent, onMounted, ref, reactive, nextTick, toRefs, watch,\n} from 'vue';\n\nexport default defineComponent({\n  name: 'Visionneuse',\n  props: ['texteEnvoye', 'taille'],\n  setup(props) {\n    const myCanvas = ref(null);\n    const carte = ref(null);\n    const { texteEnvoye: texte, taille } = toRefs(props);\n\n    const rapport = ref(0);\n    const petit = ref((window.innerWidth < 750));\n\n    const size = reactive({\n      w: window.innerWidth * taille.value,\n      h: window.innerWidth * taille.value,\n    });\n\n    function drawText() {\n      const fontSize = 0.05 * size.w - 10;\n      myCanvas.value.font = `${fontSize}px Adrip`;\n      myCanvas.value.textAlign = 'center';\n      myCanvas.value.fillStyle = 'lightgrey';\n      myCanvas.value.strokeStyle = 'black';\n      myCanvas.value.lineWidth = 0.006 * size.w - 10;\n      const x = size.w / 2;\n      const lineHeight = fontSize;\n      const lines = texte.value.split('\\n');\n      for (let i = 0; i < lines.length; i += 1) {\n        myCanvas.value.fillText(\n          lines[lines.length - i - 1],\n          x,\n          (size.h * 0.98) - (i * lineHeight),\n        );\n        myCanvas.value.strokeText(\n          lines[lines.length - i - 1],\n          x,\n          (size.h * 0.98) - (i * lineHeight),\n        );\n      }\n    }\n\n    function initCarte() {\n      const background = new Image();\n      background.src = '/img/fond.jpeg';\n      background.onload = function () {\n        rapport.value = background.naturalWidth / background.naturalHeight;\n        size.h = size.w / rapport.value;\n        nextTick(() => {\n          try {\n            myCanvas.value.drawImage(background, 0, 0, size.w, size.h);\n          } catch (e) {\n            console.log(`ERREUR DE CHARGEMENT D'IMAGE: ${e}`);\n          }\n          if (!petit.value) {\n            drawText();\n          }\n        });\n      };\n    }\n\n    function handleResize() {\n      size.w = window.innerWidth * taille.value;\n      size.h = size.w / rapport.value;\n      petit.value = window.innerWidth < 750;\n      initCarte();\n    }\n\n    window.addEventListener('resize', handleResize);\n\n    watch(texte, (_, y) => {\n      texte.value = y;\n      initCarte();\n    });\n\n    onMounted(() => {\n      const c = carte.value;\n      const ctx = c.getContext('2d');\n      myCanvas.value = ctx;\n      initCarte();\n    });\n\n    return {\n      myCanvas,\n      size,\n      texte,\n      petit,\n      carte,\n    };\n  },\n});\n\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

Aar*_*man 20

我知道你回答了你自己的问题。对于“为什么”,您不应该更改组合 API 中的 props,因为 props 用于将反应数据从父组件传递到子组件。模式是:从孩子到父母的事件,从父母到孩子的突变。 toRef使数据具有反应性,但它​​不会影响您是否可以改变它。所以如果你去:

const texteEnvoye = toRef(props, 'texteEnvoye');
texteEnvoye.value='foo'; // not allowed - texteEnvoye.value is read-only
Run Code Online (Sandbox Code Playgroud)

如果你走的话:

const texteEnvoye = ref('');
const texteEnvoyeRo = toRef(props,'texteEnvoye'); // react to prop
watch(texteEnvoyeRo, (value) => {
  textEnvoye.value = texteEnvoyeRo.value; // OK, textEnvoye is yours
});
Run Code Online (Sandbox Code Playgroud)

现在 texteEnvoye 是你的了,你可以改变它,并对 textEnvoyeRo 中的变化做出反应。


djc*_*114 3

好的,我找到了解决方案。我将“texteEnvoye”和“texte”分开,一切正常。我不知道这是否是在组合 API 中进行编码的好方法,但它确实达到了目的:

<template>
  <div class="board">
    <canvas
      ref='carte'
      :width="size.w"
      :height="size.h"
      tabindex='0'
      style="border:1px solid #000000;"
    ></canvas>
  </div>
  <div id="texteRemplacement" v-if="petit">
    <p v-for="p in texte.split('\n')" v-bind:key="p">
      {{ p }}
    </p>
  </div>
</template>

<script>

import {
  defineComponent, onMounted, ref, reactive, nextTick, toRefs, watch,
} from 'vue';

export default defineComponent({
  name: 'Visionneuse',
  props: ['texteEnvoye', 'taille'],
  setup(props) {
    const myCanvas = ref(null);
    const carte = ref(null);
    const { texteEnvoye, taille } = toRefs(props);
    const texte = ref('');

    const rapport = ref(0);
    const petit = ref((window.innerWidth < 750));

    const size = reactive({
      w: window.innerWidth * taille.value,
      h: window.innerWidth * taille.value,
    });

    function drawText() {
      const fontSize = 0.05 * size.w - 10;
      myCanvas.value.font = `${fontSize}px Adrip`;
      myCanvas.value.textAlign = 'center';
      myCanvas.value.fillStyle = 'lightgrey';
      myCanvas.value.strokeStyle = 'black';
      myCanvas.value.lineWidth = 0.006 * size.w - 10;
      const x = size.w / 2;
      const lineHeight = fontSize;
      const lines = texte.value.split('\n');
      for (let i = 0; i < lines.length; i += 1) {
        myCanvas.value.fillText(
          lines[lines.length - i - 1],
          x,
          (size.h * 0.98) - (i * lineHeight),
        );
        myCanvas.value.strokeText(
          lines[lines.length - i - 1],
          x,
          (size.h * 0.98) - (i * lineHeight),
        );
      }
    }

    function initCarte() {
      const background = new Image();
      background.src = '/img/fond.jpeg';
      background.onload = function () {
        rapport.value = background.naturalWidth / background.naturalHeight;
        size.h = size.w / rapport.value;
        nextTick(() => {
          try {
            myCanvas.value.drawImage(background, 0, 0, size.w, size.h);
          } catch (e) {
            console.log(`ERREUR DE CHARGEMENT D'IMAGE: ${e}`);
          }
          if (!petit.value) {
            drawText();
          }
        });
      };
    }

    function handleResize() {
      size.w = window.innerWidth * taille.value;
      size.h = size.w / rapport.value;
      petit.value = window.innerWidth < 750;
      initCarte();
    }

    window.addEventListener('resize', handleResize);

    watch(texteEnvoye, (x) => {
      texte.value = x;
      initCarte();
    });

    onMounted(() => {
      const c = carte.value;
      const ctx = c.getContext('2d');
      myCanvas.value = ctx;
      initCarte();
    });

    return {
      myCanvas,
      size,
      texte,
      petit,
      carte,
    };
  },
});

</script>
Run Code Online (Sandbox Code Playgroud)