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对象