【问题标题】:Vue.js component call a method inside data propertyVue.js 组件调用数据属性内的方法
【发布时间】:2021-01-10 03:20:44
【问题描述】:

我想将组件方法分配给数据变量,请参见下面的示例代码。可惜它不起作用,正确的方法是什么?

<li v-for="item in items" @click="item.action">
    {{ item.title }}
</li>
export default {
    data: () => ({
        items: [
            { title: "One", action: this.funcOne },
            { title: "Two", action: this.funcTwo },
        ]
    }),
    methods: {
        funcOne() {
            alert("Hi")
        },
        funcTwo() {
            alert("Hello")
        }
    }
}

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    尝试将vue实例(this)作为参数传递给数据函数data: (vm) =&gt;然后使用它action: vm.funcOne

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    new Vue({
      el: '#app',
          data: (vm) => ({ // vm the component instance this
            items: [
                { title: "One", action: vm.funcOne},
                { title: "Two", action: vm.funcTwo },
            ]
        }),
        methods: {
            funcOne() {
                alert("Hi")
            },
            funcTwo() {
                alert("Hello")
            }
        }
      })
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    
    
    <div id="app" class="container">
    <li v-for="item in items" @click="item.action">
        {{ item.title }}
    </li>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      相关资源
      最近更新 更多