user1012181
user1012181

Reputation: 8726

Set a vue.js data from jQuery click event

I've a Vue.js instance as follows:

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));
      }
  } 
});

I want to set the data active when I trigger the addActive method. But I think I'm unable to set the active like I'm doing it here. How can I do this?

Upvotes: 1

Views: 2836

Answers (2)

Helder Lucas
Helder Lucas

Reputation: 3343

You don't actually need jQuery for that and I think this is a more "Vue way" to do it.

Here is the working fiddle: 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 Directive:

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 Instance:

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

Upvotes: 0

Moz Morris
Moz Morris

Reputation: 6761

I'm not convinced this is idiomatic Vue but I'm sure there's a reason behind the way you're trying to do this. Anyway, this solves your problem:

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

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

Upvotes: 4

Related Questions