引用属性作为 Vue.js 组件中的 props

巴格兰

我已经开始研究棋盘游戏原型并决定使用 Vue.js。我对 JavaScript 有一些经验,一切都很顺利……直到我尝试访问组件中通过“props”传递的属性。

这是整个代码:

<!DOCTYPE HTML>

<html>

<head>
  <title>Board</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

  <style type="text/css">
    #board {
      width: 600px;
    }
    .square { width: 100px; height: 100px; margin: 1px; border: 1px solid grey; display: inline-block; float: left; }
  </style>
</head>

<body>

  <div id="board">

    <square v-for="square in squares"></square>

  </div>

  <script>
    var app = new Vue({
      el: '#board',
      data: {
        squares: []
      }
    })

    const rows = 5
    const cols = 5
    const reservedLocation = { row: 2, col: 2 }

    Vue.component('square', {
      props: [
        'row',
        'col',
        'type',
      ],
      template: '<div class="square" v-on:click="logLocation"></div>',
      methods: {
        logLocation: function() {
          console.log(this)
          console.log("Location: " + this.col + "x" + this.row )
        },
      },
    })

    for (var row=0; row<rows; row++) {
      for (var col=0; col<cols; col++) {
        const type = (row == reservedLocation.row && col == reservedLocation.col) ? 'reserved' : 'empty'
        app.squares.push({ row: row, col: col, type: type })
      }
    }

  </script>

</body>

</html>

发生的事情是“板”div 充满了“正方形”组件。每个方形组件都有“row”、“col”和“type”属性,作为“props”传递给它。当用户点击一个方块时,相应组件的“logLocation”函数被调用,该函数所做的就是记录“row”和“col”属性。

一切正常,除了记录的消息是:“位置:undefinedxundefined”,换句话说,this.col 和 this.row 似乎都未定义。我已经检查了“这个”,它似乎是正确的组件。

我确信这是显而易见的,但我无法在官方文档、教程甚至这里,堆栈溢出本身中找到答案——也许我没有使用正确的术语。

一些新信息:'row' 和 'col' 属性设置在组件对象和 '$props' 属性中,但它们返回的值是 'undefined'。我是否以某种方式错误地传递了参数?


解决方案

事实证明,Vue.js 文档中有一个部分专门用于将“v-for”与组件一起使用:“v-for with a Component”,这是代码的相关部分:

  <div id="board">

    <square
      v-for="square in squares"
      :key="square.id"
      :row="square.row"
      :col="square.col"
      :type="square.type"
    ></square>

  </div>

非常感谢斯蒂芬托马斯为我指明了正确的方向!

斯蒂芬·托马斯

您已经正确定义了 props,并且您正确地访问了 props,但是您实际上还没有将它们设置为任何值。标记:

<square v-for="square in squares"></square>

不会将道具传递给组件。也许你想要类似的东西

<div v-for="row in rows" :key="row">
    <div v-for="col in cols" :key="col">
        <square :row="row" :col="col"></square>
    </div>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章