【发布时间】:2018-12-18 06:34:53
【问题描述】:
我有三个文件:
- 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 实例并在其中声明一个方法并将其与单击事件绑定时,它可以完美运行。
我必须在哪里为我的组件声明一个方法,以便在使用<single-file-component> 标签创建的按钮上发生点击事件时调用它?
【问题讨论】:
标签: javascript vue.js vue-component