Taylor Foster
Taylor Foster

Reputation: 1215

VueJS - Sending data in markup to Vue instance to use in mounted()

I have a few different checklists for my "projects" and using the same Vue instance to handle these checklists that I am getting from my database. I am running into a problem though in which I really want to use the project's id and a type of checklist in my mounted() method to help my Controller endpoint (I'm using laravel but that is irrelevant here) point to the right database rows.

So for example:

HTML

<ul class="vue-checklist" data-project="16" data-type="permits">
</ul>

<ul class="vue-checklist" data-project="16" data-type="walkthrough">
</ul>

JS

new Vue({
    el: '.vue-checklist',
    data: {
      items: [],
      // is there a way to trap those data attrs here?
    },
    mounted : function(){
      // I need to a way to access the project and type data attrs.
      this.fetchChecklist(this.project, this.type); // <- does not work
    },
    methods: {
      fetchChecklist : function(project, type){
        this.$http.get('{ api/path }', { project: project, type: type}).then(function(response){
          this.items = response.data;
        })
      }
});

Again, is there a way to get data-project and data-type attached in the HTML use that in the mounted() method.

Upvotes: 1

Views: 959

Answers (1)

thanksd
thanksd

Reputation: 55664

You can reference the root element of the Vue instance via this.$el.

From there you can reference the element's attribute's via the getAttribute() method.

In your case, you could do something like this:

new Vue({
  el: '.vue-checklist',
  data: {
    items: [],
    project: null,
    type: null,
  },
  mounted : function(){
    this.project = this.$el.getAttribute('data-project');
    this.type = this.$el.getAttribute('data-type');
    this.fetchChecklist(this.project, this.type);
  },
  ...
}

That isn't the most straight-forward solution though. If you're able, it'd be a lot cleaner to create a Vue instance on a parent element and then define vue-checklist as a component. That way you could just pass the project and type values as props to the component from the template:

Vue.component('vue-checklist', {
  template: `<ul class="vue-checklist"></ul>`,
  props: ['project', 'type'],
  data: {
    items: [],
  },
  mounted : function(){
    this.fetchChecklist(this.project, this.type);
  },
  methods: {
    fetchChecklist : function(project, type){
      this.$http.get('{ api/path }', { project: project, type: type}).then(function(response){
        this.items = response.data;
      })
    }
  }
})

new Vue({
  el: '#app',
})
<div id="app">
  <vue-checklist project="16" type="permits"></vue-checklist>
  <vue-checklist project="16" type="walkthrough"></vue-checklist>
</div>

Upvotes: 3

Related Questions