I have this code:
new Vue({
el: '#app',
components: {
'app-component': AppComponent
},
data: {
message: 'Hello Vue.js!'
},
methods: {
doSomething: function(){
console.log('arrived!')
}
}
})
How can I call "doSomething" method from AppComponent html template? like this:
<app-component>
<a href="#" v-on:click="doSomething()">text</a>
</app-component>
I get this error:
Uncaught TypeError: scope.doSomething is not a function
试试v-on:click="$parent.doSomething()"
You can use $dispatch from the child to trigger an event. Example:
// App component
<app-component>
<a href="#" v-on:click.prevent="$dispatch('do-something')">text</a>
</app-component>
// Parent
new Vue({
el: '#app',
components: {
'app-component': AppComponent
},
data: {
message: 'Hello Vue.js!'
},
events: {
'do-something': function(){
console.log('arrived!')
}
}
});
For more info on parent-child communication, check the documentation: http://vuejs.org/guide/components.html#Parent-Child-Communication
您可以根据此答案使用此功能。
this.$parent.$options.methods.someParentMethod(data)
In addition to Wiljan response, I extend all components with new Vue instance that has methods and data. Now I access to methods and etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.