呼叫子元件方法 vue
- IT科技
- 關注:2.47W次
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
vue 呼叫子元件方法,一起來看下吧:
1、最重要的部分是在父元件呼叫子元件的標籤上,定義了一個ref屬性:child,通過這個屬性,可以獲取到子元件裡面的的屬性和方法。
2、在父元件的方法parentMethod執行的時候,使用:this.$refs.child.childMethod()來呼叫子元件的方法。
父元件程式碼:
<template> <div class="parent"> <div class="parent-wrapper"> <button @click="parentMethod">我是父元件的按鈕,但是我可以呼叫子元件的方法</button> </div> <Child ref="child"></Child> </div></template> <script>import Child from '@/components/test/Child'export default { name: 'parent', data () { return { } }, components: { Child }, methods: { parentMethod(){ this.$refs.child.childMethod(); } }}</script> <!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>.parent-wrapper { width: 300px; height: 300px; border: 1px solid red; margin: 50px;}</style>
子元件程式碼:
<template> <div class="child"> <div class="child-wrapper"> <button @click="childMethod">這是子元件的按鈕</button> </div> </div></template> <script>export default { name: 'child', data () { return { } }, methods: { childMethod() { alert("我是子元件的方法!") } }}</script> <!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>.child-wrapper { width: 300px; height: 300px; border: 1px solid blue; margin: 50px;}</style>
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/1rg2mp.html