js中想要获取dom节点一般用document.querySelecto('.input')
,然后获取input的值。 在vue中绑定ref就不需要在获取dom节点了,直接绑定在input上,然后 $refs
调用即可。$refs
的使用方法就是在元素或组件标签上添加ref
属性指定一个引用信息,引用信息将会注册在父组件的$refs
对象上,在js中使用$refs来指向DOM元素或组件实例;
1.基本用法
<template>
<div class="hello">
<p ref="testTxt">{{oldMsg}}</p>
<button @click="changeMsg()">点击修改段落内容</button>
</div>
</template>
<script>
export default {
data(){
return {
oldMsg:'这是旧数据',
newMsg:'hello,这是新数据!!!',
}
},
methods:{
changeMsg(){
this.$refs.testTxt.innerHTML=this.newMsg;
},
}
}
</script>
2.获取子组件中的数据
父组件:
<template>
<div class="parent">
<!-- 子组件标签上添加ref属性: ref="childItemId -->
<Children ref="childItemId"></Children >
<p style="color:blue;">{{msgFromChild}}</p>
<button @click="getChildMsg()">使用$refs获取子组件的数据</button>
</div>
</template>
<script>
import Children from './Children '
export default {
components:{Children },
data(){
return {
msgFromChild:'',
}
},
methods:{
getChildMsg(){
//父组件用$refs来获取子组件的数据
this.msgFromChild=this.$refs.childItemId.childMsg;
console.log(this.msgFromChild);//这是子组件的参数
//父组件用$refs来调用子组件的方法
this.$refs.childItemId.open();// 我是子组件
},
}
}
</script>
子组件:
<template>
<div class="children"></div>
</template>
<script>
export default {
data(){
return {
childMsg:'这是子组件的参数'
}
},
methods:{
open(){
console.log('我是子组件');
}
}
}
</script>