【问题标题】:Vue.js 2.5 list renderingVue.js 2.5 列表渲染
【发布时间】:2017-12-25 07:59:07
【问题描述】:

我在 JS/Vue 中有一个数组,我想在 <ul>/<li> 标签中显示它,并随着数组获得新元素而保持更新。

HTML:

<ul id="ulist">
    <li v-for="user in users">
        @{{ user }} <!-- "@" needed since this is in a laravel project with blade templates -->
    </li>
</ul>

JS:

<script>
  var socket = io('localhost:3000');

  new Vue({
     el: "#ulist",

     data: {
            users: []
           },

     mounted: function() {
        this.$nextTick(function() {
           socket.on('test-action', function(data) {
              this.users.push(data.username);
              console.log(data.username);
           }.bind(this));
        });
     }
  });
</script>

数组已正确填充(我可以通过 console.log 语句看到),但 &lt;li v-for="user in users"&gt;... 部分似乎没有工作,因为没有创建任何 &lt;li&gt;...&lt;/li&gt; 元素。我在这里做错了什么?

澄清一下:如果我将硬编码值添加到 users 数组,这些值会很好地显示在 &lt;li&gt; 元素中,但添加到数组中的其他值(在 mounted 函数中)不会显示在&lt;li&gt;...&lt;/li&gt; 元素。

编辑:版本是 2.5.13,如果重要的话

【问题讨论】:

标签: javascript laravel vue.js vuejs2


【解决方案1】:

你可以试试这个吗?

<script>
    var socket = io('localhost:3000');

    new Vue({
        el: "#ulist",

        data: {
            users: []
        },

        mounted: function() {
            var _self = this;
            this.$nextTick(function() {
                socket.on('test-action', function(data) {
                    self.users.push(data.username);
                    console.log(data.username);
                }.bind(this));
            });
        }
    });
 </script>

【讨论】:

  • _selfself 一样吗?
  • 感谢您的回答。但这对我来说似乎没有什么不同。我一直认为使用_self = this;.bind(this) 的替代方案(在某些情况下)。是对的吗?我认为不需要像您在示例中那样需要两者
【解决方案2】:

问题在于this 变量的范围。在您的代码中,这一行:

this.users.push(data.username); 

作用于 ajax 请求中的函数调用,如果您使用() =&gt;,它将在您的方法中保持当前作用域的上下文。另外,在挂载的调用中你不应该需要nextTick,所以试试这个:

<script>
    var socket = io('localhost:3000');

    new Vue({
        el: "#ulist",

        data: {
            users: []
        },

        mounted: function() {
            socket.on('test-action', data => {
                this.users.push(data.username);
                console.log(data.username);
            });
        }
    });
 </script>

虽然您使用的是 bind(this),但您在 nextTick 中使用了 this,这会导致范围问题。

还有一点值得注意,列表在 vue v 中需要 key?? (不记得是哪个了)所以使用v-for的时候最好加个key:

<ul id="ulist">
    <li v-for="(user, index) in users" :key="index">
        @{{ user }} <!-- "@" needed since this is in a laravel project with blade templates -->
    </li>
</ul>

【讨论】:

  • 感谢您的回答。使用箭头函数语法我认为我不能再使用 .bind(this) 了。那是对的吗?我尝试使用此示例,但除非删除 bind 调用,否则会导致语法错误。
  • 抱歉,这是我的一个错误。只需删除绑定,它应该一切正常。我已经更新了我的代码以适应。
猜你喜欢
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
相关资源
最近更新 更多