【发布时间】:2019-01-14 05:29:43
【问题描述】:
我正在尝试让我的代码看起来类似于 jsFiddle 工作。
代码基本上在Vue实例之外有onclick="vm.$refs.foo.addThing()"(我无法改变它的方式),它调用Vue的methods中的一个函数。
但是,它现在不起作用,我不明白为什么会这样。
HomeView.vue
var MyComponent = Vue.extend({
template: '<div><p>Hello</p><ul><li v-for="thing in things">{{ thing }}</li></ul></div>',
data: function() {
return {
things: ['first thing']
};
},
methods: {
addThing: function() {
this.things.push('another thing ' + this.things.length);
}
}
});
var vm = new Vue({
el: '#app',
components: {
'my-component': MyComponent
}
});
HTML
<div id="app">
<h1>Component Test</h1>
<my-component ref="foo"></my-component>
</div>
<button onclick="vm.$refs.foo.addThing()">External Button</button>
【问题讨论】:
-
@Andrew1325 不起作用,因为
<button> ...在 Vue 实例之外,也就是在纯 HTML 中(我无法改变它的方式)。 -
奇怪的是,这个小提琴在 Codepen 中工作正常:codepen.io/tony19/pen/NeeEbm?editors=1010
-
如果你在正文末尾链接你的js文件,这个问题可能不会出现。
标签: javascript vue.js vuejs2 vue-component