vue2 ref17 $refs 操控dom 案例
在vue中不建议安装jquery
在vue中操控dom可以用ref方法
每一个ref对象中都包含一个$refs对象,组件的$refs对象都指向一个空对象
<button @click="clg" class="red">打印</button>
methods: {
    clg(){
      console.log(this);
    },
  },
  
ref操控dom
<h1 ref="my">111</h1>
clg(){
      console.log(this);
      console.log(this.$refs.my);
      this.$refs.my.style.color = 'red'
    },
案例:
子:
<p ref="reset">值:{{cont}}</p>
<button @click="jia">+1</button>
data() {
    return {
      cont:0,
    }
  },
methods: {
    jia(){
      this.cont += 1
    },
  },
父:
<hello ref="com" @fromCount="getCount"></hello>
 <button @click="reset">重置</button>
import hello from '@/components/HelloWorld.vue'
methods: {
    reset(){
      this.$refs.com.cont = 0
    },
  },
按需填写案例:
    <input type="text" placeholder="999感冒灵" v-if="inputVi" @blur="showinpu" autofocus>
    <button v-else @click="inpu">展示</button>
data() {
    return {
      inputVi: false,
    }
  },
  methods: {
    inpu() {
      this.inputVi = true
    },
    showinpu() {
      this.inputVi = false
    },
  },
ref写法:
  $nextTick:将代码延迟到下一个dom的更新周期后实行
  focus():自动获取焦点
    <input type="text" placeholder="999感冒灵" v-if="inputVi" @blur="showinpu"  ref="iptRef">
    <button v-else @click="inpu">展示</button>
data() {
    return {
      inputVi: false,
    }
  },
  methods: {
 inpu() {
      this.inputVi = true
      this.$nextTick(()=>{
        this.$refs.iptRef.focus()
      })
    },
    showinpu() {
      this.inputVi = false
    },
  },
    代码改变了我们,也改变了世界

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号