VueJS / jQuery通过单击按钮从P标签获取价值

时间:2019-03-20 18:48:57

标签: jquery vue.js

单击按钮时,我需要获取商品价格。这是我目前的代码:

   <div id="shop" class="row" v-cloak>
    {{#each items}}
        <img src="{{img}}">
        <p>{{title}}</p>
        <p class="price">{{price}}</p><br>
        <button class="btn btn-danger" @click="buyItem">Buy</button>
    {{/each}}
   </div>

JS:

    methods: {
        buyItem: function(event){    
            console.log($( event.target ).closest( ".price" ).text());
        }
    }

这将在console.log中返回空白行。如何获得该price值?

编辑

server.js(从此处获取项目):

            res.render('game/index', {
                items
            });

使用胡子来显示项目:

index.hbs:

      <div id="shop" class="row" v-cloak>
    {{#each items}}
        <img src="{{img}}">
        <p>{{title}}</p>
        <p class="price">{{item.price}}</p><br>
        <button class="btn btn-danger" @click="buyItem">Buy</button>
    {{/each}}
      </div>

2 个答案:

答案 0 :(得分:1)

您应该在事件处理程序中将价格作为参数传递:

... @click="buyItem(price)" ...

您的buyItem将变为:

methods: {
        buyItem: function(price){    
            console.log(price);
        }
    }

答案 1 :(得分:0)

请参见https://jsfiddle.net/mykwgo8x/1/

   <div id="shop" class="row" v-cloak>
      <!-- use v-for directive, not {{#each items}} -->
      <div v-for="item in items">
          <!-- <img src="{{item.img}}"> -->
          <!-- properties need to be accessed with "item." -->
          <p>{{item.title}}</p>
          <p class="price">{{item.price}}</p><br>
          <button class="btn btn-danger" @click="buyItem(item)">Buy</button>
      </div>
   </div>
new Vue({
  el: "#shop",
  data: {
    items: [
      {
        title: "item 1",
        price : 10
      },
      { 
        title : "item 2",
        price: 2
      }
    ]
  },
  methods: {
    buyItem: function(item){
        console.log(item.price);
    }
  }
})