Why can't Vue find the variable in the loop?
P粉727531237
P粉727531237 2024-02-17 12:57:37
0
2
491

I'm trying to develop a simple component and use it in a loop:

<template id="measurement">
    <tr class="d-flex">
    </tr>
</template>
Vue.component('measurement', {
    template: '#measurement',
    props: {
        name: String,
        data: Object,
        val: String,
    },
});

This obviously doesn't work yet, but it has failed:

<table v-for="(m, idx) in sortedMeters">
    <measurement v-bind:data="m"></measurement>
</table>

gives ReferenceError: Variable not found in view: m. For a strange reason the same thing works in paragraphs, i.e. there are no errors:

<p v-for="(m, idx) in sortedMeters">
    <measurement v-bind:data="m"></measurement>
</p>

What causes the variable to not be found?

PS: This is a fiddle: https://jsfiddle.net/andig2/u47gh3w1/. Once table is included a different error is displayed.

Update The purpose of the loop is to generate multiple tables. The number of rows in each table will be created by multiple measurement

P粉727531237
P粉727531237

reply all(2)
P粉921165181

If replaced


and

You will end up with working code.

But you will most likely want to use


or


P粉488464731

TLDR: Before Vue passes the DOM template, the browser will <measurement v-bind:name="i" v-bind:data="m"> Promoted outside of <table> (outside the v-for context), causing an error in Vue. This is a known warning of DOM template parsing.


The HTML specification requires that <table> contain only certain child elements :

  • <script> or
  • Similarly, 's<a href="https://html.spec.whatwg.org/multipage/tables.html#the-tr-element" rel="nofollow noreferrer">content model&lt ;tr> is:

    • <script> or
    • Compatible browser DOM parsers will automatically elevate disallowed elements (such as <measurement>) out of the table. This happens before the script stage (before Vue even sees it).

      For example, this tag:

      
      

      ...after DOM parsing (before any scripting) becomes this:

       
      

      Note how i and m are outside the context of the v-for loop, which leads to concerns about i and m are undefined Vue runtime errors (unless your component happens to have declared them). The purpose of m is to bind to the data property of <measurement>, but due to failure, data is just its initial value (also undefined), causing the rendering of {{data.value}} to fail. cphpcn rendering error: "TypeError: Cannot read property 'value' of undefined" .

      To demonstrate boosting without these runtime errors and without Vue, run the following code snippet:

      
      
      1. hoisted outside
      2. also hoisted outside
      3. inside table
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template