javascript - Vue.js 调用组件/实例方法

标签 javascript vue.js vue-component

我有三个文件:

  • SingleFileComponent.js
  • app_index.js
  • index.html

我在“SingleFileComponent.js”文件中声明我的模板,将其导入“app_index.js”中,在那里创建我的 Vue 实例,然后将两者导入到我使用的“index.html”中

<single-file-component></single-file-component>

创建一个按钮。

SingleFileComponent.js

export default {
    template:"<button type='button' value='test'>{{ text }}</button>",
    props: [
        'text',
    ]
}

app_index.js

import SingleFileComponent from './SingleFileComponent.js';

new Vue({
    el: '#app',
    components: {
        SingleFileComponent,
    },
    methods: {
        on_click: function() {
            alert('import')
        }
    }
});

index.html

<html>
<head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="#">
    <script src="vue.min.js"></script>
    <title>Vue.js Single File Component</title>
</head>
<body>
    <div id="app">
        <single-file-component id="test" text="Test" @click="on_click()"></single-file-component>
    </div>
    <div>
        <button type="button" id="direct" @click="onclick()">Direct</button>
    </div>
    <script>
        var direct = new Vue({
            el: '#direct',
            methods: {
                onclick: function() {
                    alert('Direct instance')
                }
            }
        })
    </script>
    <script type="module" src="singlefilecomponent.js"></script>
    <script type="module" src="app_index.js"></script>
</body>
</html>

当点击事件发生时,我想从我的 Vue 实例调用“on_click”方法。但它没有调用它,也没有给我一个错误。

当我替换时,它也不会调用任何东西

methods: {
    on_click: function() {
        alert('import')
    }
}

filters: {
    on_click: function() {
        alert('import')
    }
}

如上所述,我在实例('app_index.js')中声明了该方法,但该方法不起作用。

然后我在组件('SingleFileComponent.js')中声明了它,但它也不起作用。

但是当我在 HTML 文件本身中创建一个 Vue 实例并在那里声明一个方法并将其与单击事件绑定(bind)时,它可以完美地工作。

我必须在哪里为我的组件声明一个方法,以便当按钮上发生单击事件时调用它,该按钮是用 <single-file-component> 创建的标签?

最佳答案

修改SingleFileComponent.js

export default {
  template:"<button type='button' v-on:click="onClick"  value='test'>{{ text }}</button>",
  props: [
    'text',
  ],
  methods: {
    onClick: function(e) {
      console.log('e: ', e);
      alert('onClick method is invoked!');
    }
  }
}

关于javascript - Vue.js 调用组件/实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51264801/

相关文章:

javascript - 在解决 promise 之前,函数正在重新调整未定义

vue.js - 在 V-CALENDAR Vuetify Vuejs 中显示来自 Api 的数据

vue.js - vue组件注册和路由

javascript - 如何在 Vue 中单击时更改按钮类?

javascript - Css3 过渡模糊闪烁的边缘

javascript - knockout 改变一个变量的值

vue.js - Vue Storybook Jest Addon 配置问题

javascript - var questionsRight 不是添加正确答案

javascript - Js事件离开页面和返回

vue.js - 视觉 : method is not a function within inline-template component tag