vue中ref的用法

一、获取dom元素

<div ref="myref">tttt</div>

let myDOM = this.$refs.myref;

二、获取子组件中的data

// 子组件
<template>
  <div>
    我是子组件
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "myhua"
    };
  }
};
</script>


// 父组件

<template>
  <div id="app">
    <Son ref="myref"></Son>
  </div>
</template>

<script>
import Son from "./components/son";
export default {
  mounted() {
    console.log(this.$refs.myref.name); //输出子组件data中的name的值:myhua
  },
  components: {
    Son
  }
};
</script>

三、调用子组件中方法

// 子组件
<template>
  <div>
    我是子组件
  </div>
</template>

<script>
export default {
  methods: {
    logName() {
      console.log("myhua!!");
    }
  }
};
</script>


// 父组件

<template>
  <div id="app">
    <Son ref="myref"></Son>
  </div>
</template>

<script>
import Son from "./components/son";
export default {
  mounted() {
    this.$refs.myref.logName();//子组件中的方法
  },
  components: {
    Son
  }
};
</script>

猜你喜欢

转载自blog.csdn.net/weixin_45818290/article/details/126739477
今日推荐