我一直在寻找解决方案和参考我的问题。我很困惑通过外部按钮调用VueJs组件内部的vue方法(例如:createItem(){...})。
这是我的“app.js”
// ..\resources\assets\js\app.js
require('./bootstrap');
window.Vue = require('vue');
window.Vue.prototype.$http = axios;
Vue.component('sample', require('./components/SampleComponent.vue'));
const app = new Vue({
el: '#app',
methods: {
createItem: function() {
// what's here?
}
}
});
SampleComponent.vue
<template>
...
</template>
<script>
export default {
mounted() {
this.getItems();
},
data() {
return {
items: [],
newItem: {'name': '', 'description': ''},
fillItem: {'id': '', 'name': '', 'description': ''}
}
},
methods: {
getItems() {
axios.get( 'api/data' ).then( response => {
let answer = response.data;
this.items = answer;
})
},
clearItem(){
this.newItem = {'name': '', 'description': ''};
this.fillItem = {'id': '', 'name': '', 'description': ''};
},
createItem(){
var self = this;
$("#create-role").on("hidden.bs.modal", function () {
self.clearItem();
}).modal('show');
},
}
}
</script>
index.blade.php
<div id="app>
...
<!-- Load samplecomponent to blade -->
<sample></sample>
<!-- An external button to call method inside SampleComponent.vue, How can I do this? -->
<button type="button" class="btn btn-sm" @click="createItem" id="external-button">Create new item</a>
</div> <!-- End App -->
我已阅读该指南,但仍然失败。对不起这个新手问题,我刚刚使用了VueJS。谢谢你的帮助。
答案 0 :(得分:0)
您的标记已被破坏,因为class Script(object):
def __init__(self, data1, data2, data3):
self.data1 = data1
self.data2 = data2
self.data3 = data3
def getData1(self):
return self.data1
def getData2(self):
return self.data2
def getData3(self):
return self.data3
def run(self):
return 'Running successfully'
script1 = Script('data1', 'data2', 'data3')
print script1.run()
已关闭<button>
而不是</a>
</button>
此外,<button ... @click="createItem" id="external-button">Create...</a>
是一个函数,因此请务必添加括号!
更正后的代码:
createItem
答案 1 :(得分:0)
您可以使用ref
来调用子方法:
标记:
<div id="app>
<sample ref="child"></sample>
<button type="button" class="btn btn-sm" @click="callChildCreateItem" id="external-button">Create new item</a>
</div>
父:
const app = new Vue({
el: '#app',
methods: {
callChildCreateItem: function() {
this.$refs.child.createItem()
}
}
});
或者,您可以使用事件(可能是插件like这使事情变得更容易)
父:
const app = new Vue({
el: '#app',
methods: {
callChildCreateItem: function() {
this.$events.fire('childCreateItem')
}
}
});
子:
export default {
...
methods: {
...
createItem(){
...
},
},
events: {
childCreateItem () {
this.createItem()
}
},
}