天天看點

Vue學習記錄--使用ref擷取DOM元素群組件引用

使用 ​

​this.$refs​

​ 來擷取元素群組件

<div id="app">
    <div>
      <input type="button" value="擷取元素内容" @click="getElement" />
      <!-- 使用 ref 擷取元素 -->
      <h1 ref="myh1">這是一個大大的H1</h1>

      <hr>
      <!-- 使用 ref 擷取子元件 -->
      <my-com ref="mycom"></my-com>
    </div>
  </div>

  <script>
    Vue.component('my-com', {
      template: '<h5>這是一個子元件</h5>',
      data() {
        return {
          name: '子元件'
        }
      }
    });

    // 建立 Vue 執行個體,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getElement() {
          // 通過 this.$refs 來擷取元素
          console.log(this.$refs.myh1.innerText);
          // 通過 this.$refs 來擷取元件
          console.log(this.$refs.mycom.name);
        }
      }
    });
  </script>      
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <input type="button" value="擷取元素" @click="getElement" ref="mybtn">

    <h3 id="myh3" ref="myh3">哈哈哈, 今天天氣太好了!!!</h3>

    <hr>

    <login ref="mylogin"></login>
  </div>

  <script>

    var login = {
      template: '<h1>登入元件</h1>',
      data() {
        return {
          msg: 'son msg'
        }
      },
      methods: {
        show() {
          console.log('調用了子元件的方法')
        }
      }
    }

    // 建立 Vue 執行個體,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getElement() {
          // console.log(document.getElementById('myh3').innerText)

          //  ref  是 英文單詞 【reference】   值類型 和 引用類型  referenceError
           console.log(this.$refs.myh3.innerText)

          // console.log(this.$refs.mylogin.msg)
           this.$refs.mylogin.show()
        }
      },
      components: {
        login
      }
    });
  </script>
</body>

</html>