Vue中操作dom---ref的使用

<h1 ref="myh1">App 根组件--{{countFromSon}}</h1>
showThis(){
      console.log(this)
      this.$refs.myh1.style.color='red'
    }

 

 

ref引用组件示例

//子组件
<template>
<div class="right-container">
<h3>Right 组件---{{count}}</h3>
<button @click="add">+1</button>
<button @click="resetCount">重置</button>
<hr>
<p>{{msgFromLeft}}</p>
</div>
</template>

<script> import eventBus from "@/components/eventBus"; export default { data(){ return{ count:0, msgFromLeft:'' } }, methods:{ add(){ this.count++ this.$emit('numChange',this.count) }, resetCount(){ this.count=0 } }, created() { eventBus.$on('share',(val)=>{ this.msgFromLeft=val }) } } </script>
<template>
  <div class="app-container">
    <h1 ref="myh1">App 根组件--{{countFromSon}}</h1>
    <p>{{userinfo}}</p>
    <button @click="showThis">打印this</button>
    <button @click="onReset">重置Left组件的count值为0</button>
    <hr />

    <div class="box">
      <!-- 渲染 Left 组件和 Right 组件 -->
      <Left :msg="message" :user="userinfo" ></Left>
      <Right @numChange='getNewCount' ref="comRight"></Right>
    </div>
  </div>
</template>

<script>

import Left from "@/components/Left";
import Right from "@/components/Right";
export default {
  data(){
    return{
      message:'123112',
      userinfo:{name:'wsc',age:18},
      countFromSon:0
    }
  },
  components:{
    Left,
    Right
  },
  methods:{
    getNewCount(val){
        this.countFromSon=val
    },
    showThis(){
      console.log(this)
      this.$refs.myh1.style.color='red'
    },
//两种方式控制子组件dom
//1.控制子组件的函数
//2.直接通过ref控制父组件 onReset(){
/*this.$refs.comRight.resetCount()*/ this.$refs.comRight.count=0 } } } </script>

 

posted @ 2022-03-17 22:26  眼里无光  阅读(193)  评论(0)    收藏  举报