當前位置:生活全書館 >

IT科技

> 調用子組件方法 vue

調用子組件方法 vue

<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>

vue 調用子組件方法

標籤: 調用 vue 組件
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zh-mo/dianzi/1rg2mp.html