VueJS - 将标记中的数据发送到Vue实例以在mounted()中使用

时间:2017-06-28 13:26:14

标签: javascript vue.js vuejs2

我为我的“项目”提供了一些不同的清单,并使用相同的Vue实例来处理我从数据库中获取的这些清单。我遇到了一个问题,虽然我真的想在我的id方法中使用项目的typemounted()清单来帮助我的Controller端点(我正在使用laravel但是这里无关紧要)指向正确的数据库行。

例如:

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

同样,有没有办法在data-project方法的HTML使用中附加data-typemounted()

1 个答案:

答案 0 :(得分:3)

您可以通过this.$el引用Vue实例的根元素。

从那里你可以通过getAttribute()方法引用元素的属性。

在你的情况下,你可以这样做:

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

这不是最直接的解决方案。如果你能够,那么在父元素上创建Vue实例然后将vue-checklist定义为组件会更加清晰。这样您就可以将projecttypeprops传递给模板中的组件:

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>