从jQuery click事件设置vue.js数据

时间:2015-11-11 16:52:37

标签: jquery vue.js

我的Vue.js个实例如下:

new Vue({
  el: '#app',
  data: {
      active: ''
  }
  methods: {
      addActive: function(){
         $(document).on('click', '[prop-name]', function(){
                this.active = {name: $('this').attr('prop-name'), latitude: $('this').attr('prop-lat'), longitude: $('this').attr('prop-long'), icon: $('this').attr('prop-icon')};
            }.bind(this));
      }
  } 
});

我想在触发active方法时设置数据addActive。但我想我无法设置active,就像我在这里做的那样。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

我不相信这是惯用的Vue,但我确信你尝试这样做的方式背后有一个原因。无论如何,这解决了你的问题:

// Calculate the int that will be convert to Hex string
int totalLenght=11+request.Length;  
// Try to convert it into byte
byte totalLenghtByte=Convert.ToByte( totalLenght.ToString("X"));  
// put it into an array of bytes
xbeeFrame[2] =(totalLenghtByte); 

Jsfiddle:https://jsfiddle.net/3hbr9rza/

答案 1 :(得分:0)

你实际上并不需要jQuery,我认为这是一种更多的" Vue方式"这样做。

这是工作小提琴: http://jsfiddle.net/q4ky8g9r/

HTML:     

   <div v-for="prop in props"
        v-set-active-prop="active"
        prop-name="test-{{$index}}" 
        prop-lat="1.111" 
        prop-long="2.2222" 
        prop-icon="icon.png"
        class="xpto"
    >
       I have many props (click me)
    </div>

    <div v-if="active">
        <p>{{active.name}}</p>
        <p>{{active.lat}}</p>
        <p>{{active.long}}</p>
        <p>{{active.icon}}</p>
    </div> 

</div>

Vue指令:

Vue.directive('set-active-prop', {
  twoWay: true,
  bind: function () {
      var el = this.el,
          self = this;

      el.addEventListener("click", function() {
          var active = {
            name: el.getAttribute('prop-name'),
            lat: el.getAttribute('prop-lat'),
            long: el.getAttribute('prop-long'),
            icon: el.getAttribute('prop-icon')
        }
        self.set(active);
      });
  },
  update: function (newValue, oldValue) {


  },
  unbind: function () {}
})

Vue实例:

new Vue({
  el: '#app',
  data: {
      props: 4,
      active: {
         name: null,
         lat: null,
         long: null,
         icon: null
      }
  },
});