【问题标题】:Function call inside a template模板内的函数调用
【发布时间】:2017-04-25 09:48:44
【问题描述】:

我有一个用于简单分页表格的 vue 组件。我需要在鼠标悬停时突出显示所述表格的一行。到目前为止,我所做的是创建模板并创建动态加载的 ajax 驱动的下一个和上一个按钮。问题在于突出显示,因为它是一个动态元素。

这是模板代码:

<tbody class="table-body">
    <template id="template-student">
        <tr @mouseover="highlightRow()" class="students-row" data-student-url="{{ URL::route("student", 1) }}">
            <td>
                <div class="student-image">
                    <div class="flag"></div>
                </div>
            </td>
            <td>
                <a href="">@{{ student.student_firstname }}</a>
            </td>
            <td>
                <a href="">@{{ student.student_lastname }}</a>
            </td>
            <td>
                @{{ student.student_telephone }}
            </td>
            <td>
                @{{ student.student_fathersname }}
            </td>
        </tr>
    </template>
</tbody>

还有vue代码:

Vue.component('student', {
    template: '#template-student',
    props: ['student'],
  });
  new Vue({
    el: '#app',
    data: {
      students: [],
      pagination: {}
    },
    ready() {
      this.fetchStudents();
    },
    methods: {
      fetchStudents(pageNumber) {
        if (pageNumber === undefined) {
          pageNumber = 1;
        }
        const vm = this;
        const pageUrl = `/api/on-roll/all/${pageNumber}`;
        this.$http.get(pageUrl)
            .then((response) => {
              vm.makePagination(response.data.pagination);
              vm.$set('students', response.data.data);
        });

      },
      makePagination(data) {
        const pagination = {
          current_page: data.current_page,
          total_pages: data.total_pages,
          next_page: data.next_page,
          prev_page: data.prev_page
        };
        this.$set('pagination', pagination);
      },
      highlightRow(){
        console.log("test")
      }

    }
  });

问题是当我将鼠标悬停在任何行上时都会出现错误:

Uncaught TypeError: scope.highlightRow is not a function

现在我(或多或少)理解为什么会发生这种情况,我在模板标签内调用了一个函数(如果我在示例元素的外部调用它可以工作)。一些研究使我想到了这个问题dynamical appended vuejs content: scope.test is not a function 但是那里的帮助对我没有帮助。我不知道如何实现我的示例的解决方案。

【问题讨论】:

  • 用 CSS 做就行了,这里不需要任何代码:tr:hover td { background: red; }
  • 啊,成功了。我仍然想要一个实际的解决方案,因为我需要它来处理其他事情。

标签: javascript laravel scope vue.js


【解决方案1】:

任何时候您希望组件可以访问父级的某些内容,请将其作为道具传递。

new Vue({
  el: '#app',
  components: {
    myComponent: {
      template: '<div @mouseover="onHover">Hi</div>',
      props: ['onHover']
    }
  },
  methods: {
    highlightRow() {
      console.log('test');
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <my-component :on-hover="highlightRow"></my-component>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多