vue中获取页面里的某个元素(标签或组件),可以给它绑定ref属性,有点类似于给它添加id名。
- <template>
- <div class="">
- <h3 ref="title">{{msg}}h3>
- <button @click="btnclick">按钮button>
- div>
- template>
-
- <script>
- export default {
- data() {
- return {
- msg: "你好"
- };
- },
- methods: {
- btnclick() {
- console.log(this.$refs.title); // 得到h3标签
- }
- }
- };
- script>
-
- <style lang = "less" scoped>
- style>
子组件:

父组件:
- <template>
- <div>
- <p ref="op">这是p标签p>
- <button @click="hdClick">按钮button>
- <Child ref="chd"/>
- div>
- template>
-
- <script>
- import Child from "./Comp8Child.vue"
- export default {
- data () {
- return {
-
- }
- },
- components:{
- Child
- },
- methods:{
- hdClick(){
- // this.$refs对象,专门来接收这个组件中带有ref属性的标签/子组件,作为自己的属性
- console.log(this.$refs.op.innerHTML);
- this.$refs.op.style.color = "red";
- console.log(this.$refs.chd.cnum);
- this.$refs.chd.childFn()
- }
- }
- }
- script>
-
- <style lang = "less" scoped>
-
- style>