ref 被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的 $refs 对象上
- 获取本页面的dom元素
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title></title>
</head>
<body>
<div id="app">
<div ref="box">{{message}}</div>
<input type="text" v-model="message">
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
message: 'hello vue.js.'
},
watch: {
},
computed: {
},
created() {
// this.getBox()
},
mounted() {
this.getBox()
},
methods: {
getBox() {
let ref = this.$refs
let refBox = ref.box
console.log(refBox)
}
},
});
</script>
</html>
- 获取子组件的data属性
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title></title>
</head>
<body>
<div id="app">
<div ref="box">{{message}}</div>
<input type="text" v-model="message">
<world ref="world"></world>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#app',
components: {
'world': {
name:"world",
template: '<div>{{msg}}</div>',
data() { //
return {
msg: 'This is a Child Component1!'
}
}
},
},
data: {
message: 'hello vue.js.'
},
watch: {
},
computed: {
},
created() {
// this.getBox()
},
mounted() {
this.getWorld()
},
methods: {
getWorld() {
let refBox = this.$refs.world.msg
console.log(refBox)
}
},
});
</script>
</html>
3. 调用子组件的方法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title></title>
</head>
<body>
<div id="app">
<div ref="box">{{message}}</div>
<input type="text" v-model="message">
<world ref="world"></world>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#app',
components: {
'world': {
name: "world",
template: '<div>{{msg}}</div>',
data() { //
return {
msg: 'This is a Child Component1!'
}
},
methods: {
getData() {
console.log('我是子组件中的方法')
}
},
},
},
data: {
message: 'hello vue.js.'
},
watch: {
},
computed: {
},
created() {
// this.getBox()
},
mounted() {
this.getWorld()
},
methods: {
getWorld() {
this.$refs.world.getData()
}
},
});
</script>
</html>