如何在Vue本地组件上使用功能

时间:2020-02-25 10:33:21

标签: vue.js vue-component

在我的示例js代码中:

new Vue({
  el: '#app',
  data: {
    list: [1,2,3]
  },
  methods: {
    change: function(number) {
      return number === 2 ? 'a' : 'b';
    }
  },
  components: {
    'html-list': {
      props: ['item'],
      template: '<li :title='change(item)'> text </li>'
    }
  }
});
在我的示例html代码中,

是:

<ul id='app'>
  <html-list
    v-for:'num in list'
    :item='num'
  ></html-list>
</ul>

我想要以下结果:

<ul id='app'>
  <li title='b'> text </li>
  <li title='a'> text </li>
  <li title='b'> text </li>
</ul>

但是它不起作用。

我尝试了几种不同的方法,但是找不到通过在组件上调用函数来动态绑定数据的方法。

我不想使用全局组件,因为要创建的组件太多。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您尝试使用change函数,该函数未在component中声明。

有几种解决方案:

  1. 在组件中声明函数
components: {
  'my-component': {
    props: [...],
    template: '...',
    methods: {
      change: function() {...}
    }
  }
}
  1. 如果要使用父组件template: '<li :title='$parent.change(item)'> text </li>'中的功能
  2. 使用Vuex