vue中ref的作用


1.基本用法,本頁面獲取dom元素:

<template>
  <div id="app">
    <div ref="testDom">11111</div>
    <button @click="getTest">獲取test節點</button>
  </div>
</template>

<script>
export default {
  methods: {
    getTest() {
      console.log(this.$refs.testDom)
    }
  }
};
</script>

 

其實ref除了可以獲取本頁面的dom元素,還可以拿到子組件中的data和去調用子組件中的方法:

2 獲取子組件中的data:

子組件:

<template>
  <div>
      {{ msg }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "hello world"
    }
  }
}
</script>

父組件

<template>
  <div id="app">
    <HelloWorld ref="hello"/>
    <button @click="getHello">獲取helloworld組件中的值</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {}
  },
  methods: {
    getHello() {
      console.log(this.$refs.hello.msg)
    }
  }
};
</script>

 

 

 

 

3.調用子組件中的方法

子組件:

<template>
  <div>
  </div>
</template>

<script>
export default {
  methods: {
    open() {
      console.log("調用到了")
    }
  }
}
</script>

父組件:

<template>
  <div id="app">
    <HelloWorld ref="hello"/>
    <button @click="getHello">獲取helloworld組件中的值</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {}
  },
  methods: {
    getHello() {
      this.$refs.hello.open();
    }
  }
};
</script>

 

 

 

 

 

轉載自:https://www.jianshu.com/p/623c8b009a85


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM