Vue-ref是什么?
# ref是什么?
# 基本用法,本页面获取dom元素
<template>
<div id="app">
<div ref="testDom">11111</div>
<button @click="getTest">获取test节点</button>
</div>
</template>
1
2
3
4
5
6
7
2
3
4
5
6
7
<script>
export default {
methods: {
getTest() {
console.log(this.$refs.testDom)
}
}
};
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 获取子组件中的data
子组件:
<template>
<div>
{{ msg }}
</div>
</template>
1
2
3
4
5
2
3
4
5
<script>
export default {
data() {
return {
msg: "hello world"
}
}
}
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
父组件:
<template>
<div id="app">
<HelloWorld ref="hello"/>
<button @click="getHello">获取helloworld组件中的值</button>
</div>
</template>
1
2
3
4
5
6
2
3
4
5
6
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
components: {
HelloWorld
},
data() {
return {}
},
methods: {
getHello() {
console.log(this.$refs.hello.msg)
}
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 调用子组件中的方法
<template>
<div>
</div>
</template>
1
2
3
4
2
3
4
<script>
export default {
methods: {
open() {
console.log("调用到了")
}
}
}
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
父组件:
<template>
<div id="app">
<HelloWorld ref="hello"/>
<button @click="getHello">获取helloworld组件中的值</button>
</div>
</template>
1
2
3
4
5
6
2
3
4
5
6
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
components: {
HelloWorld
},
data() {
return {}
},
methods: {
getHello() {
this.$refs.hello.open();
}
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2024/08/14, 04:14:33