【问题标题】:Multiple buttons with same function call, but alert only showing for the first button具有相同功能调用的多个按钮,但仅显示第一个按钮的警报
【发布时间】:2019-09-02 00:48:33
【问题描述】:

我一直在搞乱 Vue.js 和 Django,我在按钮上添加了一个函数调用。对于每种不同类型的食物,该按钮会多次显示,但仅在单击第一个按钮时才会显示警报。可能是什么原因?

Django 模板:

{%if context%}
{%for fooditem in context%}
<div id = "vue-app2">
<button class = "btn-foodname" v-on:click="changeFoodName()">{{fooditem.food_name}}</button>
<p>{{fooditem.country_of_origin}}</p>
</div>
{%endfor%}
{%else%}
<p>Nothing to see here</p>      
{%endif%} 

JS:

var x = new Vue({
    el: '#vue-app2',
    data:{
        new_message: 'Yes, this is a good food!'
    },
    methods:{
        changeFoodName: function(){
            alert(this.new_message);
        }
    }
});

【问题讨论】:

    标签: javascript django vue.js


    【解决方案1】:

    想通了。我在 for 循环中有 div,所以它为每个按钮创建了一个新的 div。

    【讨论】:

      【解决方案2】:

      问题在于,您使用模板创建了多个具有相同应用程序 ID 的块。应该是这样的:

      {%if context%}
        <div id = "vue-app2">
        {%for fooditem in context%}
          <div>
            <button class = "btn-foodname" v-on:click="changeFoodName()">
              {{fooditem.food_name}}
            </button>
            <p>{{fooditem.country_of_origin}}</p>
          </div>
        {%endfor%}
        </div>
      {%else%}
        <p>Nothing to see here</p>       
      {%endif%} 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 2019-02-23
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多