首页 > 解决方案 > 从 Vue 模板中读取所有元素绑定

问题描述

我正在尝试预处理 Vue 2 模板并获取所有元素绑定的列表。因此,如果我有这样的文件:

<html>
<body>
<div id="app">
    <p>Here's a message: {{message1}}</p>
    <p>Here's an input: <input type="text" v-model="message2"></p>
</div>

<script type="application/javascript" src="vue.js"></script>
<script type="application/javascript">
    new Vue({
        el: "#app",
        data: {
            message1: "foo",
            message2: "bar"
        }
    });
</script>
</body>
</html>

然后某个地方(在Mount 之前?)我可以查询Vue,它会告诉我绑定是['message1','message2']。那可能吗?

标签: vue.jsvuejs2

解决方案


我最终通过获取渲染函数的文本(通过调用 vm.$options.render.toString() )然后从中解析绑定来解决这个问题。

例如,简单列表视图的渲染函数如下所示:

function() {
  var _vm = this
  var _h = _vm.$createElement
  var _c = _vm._self._c || _h
  return _c(
    "table",
    { attrs: { border: "1", cellpadding: "5", cellspacing: "0" } },
    [
      _vm._m(0),
      _vm._l(_vm.rows, function(row) {
        return _c("tr", [
          _c(
            "td",
            [
              _c("router-link", { attrs: { to: "/detail/" + row.ID } }, [
                _vm._v(_vm._s(_vm._f("truncate")(row.TITLE, 100)))
              ])
            ],
            1
          ),
          _c("td", [_vm._v(_vm._s(_vm._f("truncate")(row.DESCRIPTION, 200)))]),
          _c("td", [_vm._v(_vm._s(row.TYPE))])
        ])
      })
    ],
    2
  )
}

看起来绑定总是包含在 _s() 元素中,并且在使用过滤器时可以选择vm.f () 指令。


推荐阅读