Vue使用ref 属性来获取DOM
2024-08-26 12:23:41
注意,在父组件中可以使用this.$refs.属性名 获取任何元素的属性和方法,子组件不可以获取父组件中的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
<div class="app">
<input type="button" @click="show" value="点击">
<!-- 设置元素ref 属性 -->
<h1 ref="chuandi">中国是伟大的祖国</h1>
<hr>
<log ref="mylog"></log>
</div> <template id="log">
<div>
<input type="button" value="获取元素" @click="comfunc">
<h1>你说的很对啊</h1>
</div>
</template> <script>
var vm=new Vue({
el:'.app',
data:{},
methods: {
show(){
// 获取ref属性为chuandi的内部文本
console.log(this.$refs.chuandi.innerText); //获取到了h1 元素的文本
console.log(this.$refs.mylog.name); //获取到了子组件的data属性
console.log(this.$refs.mylog.add); //获取到了子组件的方法 }
}, components:{
log:{
template:'#log',
data(){
return{
name:'duwei'
}
},
methods: {
add(){ console.log('调用了子组件的方法'); },
comfunc(){
console.log(this.$refs.chuandi.innerText); //报错 innerText没有定义, 子组件不能通过ref 来获取父组件的属性方法
// 需要使用props }
},
} }
})
</script>
</body>
</html>
最新文章
- 530 User cannot log in, home directory inaccessible.
- 在计算机 . 上没有找到服务 WAS
- selenium获取html的表格单元格数据
- 获取php的配置
- hadoop2 作业执行过程之yarn调度执行
- 测试使用Windows Live Writer
- 后台地址报错:Service Unavailable
- 子查询有OR无法展开,改写成union
- #ifndef #define #endif 防止头文件被重复引用
- aspose.words 处理word转PDF
- HDU 2087 剪花布条 KMP
- 201521123098 《Java程序设计》第14周学习总结
- 大话python模块与包
- Django中不返回QuerySets的API -- Django从入门到精通系列教程
- Kafka--消息队列
- 3173. 【GDOI2103模拟3.17】扫雷游戏(搜索 + 剪枝)
- 让wampserver2.5.exe支持sql server数据库的方法
- iptables精通
- grid的简单使用
- VB6 red write DB using Microsoft DAO 3.6 Object Library