【Vue-cli ref的引用】

ref的引用

//app.vue
<template>
  <div id="app">
    <!-- 组件引入是用两个单词首字母大写的方式引入的
    可以使用小写加-分割 -->
    
    <child-new ref="childnew"/>
  </div>
  
</template>
<script>
import ChildNew from '@/components/ChildNew'
export default {
      name: 'App',
      components:{
        ChildNew,
      },
      
    mounted(){
        /* 获得子组件的dom元素 */
        console.log(this.$refs.childnew);
        
        /* 在父组件里面去操作子组件的dom元素 */
         this.$refs.childnew.$el.innerHTML = "<h1>我修改了子组件里面的元素内容</h1>" 
         
        /* 触发子组件内部的方法 */
         this.$refs.childnew.toast(); 
         
        /* 获取子组件内部data的属性 */
         console.log(this.$refs.childnew.aa); 
         
        /* 定义一个子组件 在父组件上通过ref 把子组件的整个背景改成红色 */
        this.$refs.childnew.$el.style.background = 'red';
  },
}
</script>

this.$nextTick(cb)方法

等组件的DOM更新完成之后,在执行cb回调函数。从而保证cb回调函数可以操作最新的DOM元素

<template>
  <section>
    <div ref="hello">
      <h1>Hello World ~</h1>
    </div>
    <el-button type="danger" @click="get">点击</el-button>
  </section>
</template>
<script>
  export default {
    methods: {
      get() {
      }
    },
    mounted() {
      console.log(333);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(444);
        console.log(this.$refs['hello']);
      });
    },
    created() {
      console.log(111);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(222);
        console.log(this.$refs['hello']);
      });
    }
  }
</script>

在这里插入图片描述


可以根据打印的顺序看到,在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作并无作用,而在created()里使用this.$nextTick()可以等待dom生成以后再来获取dom对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值