跳至主要內容

Vue2 ref 引用

望间代码VueVue2小于 1 分钟

Vue2 ref 引用

Vue 提供获取 DOM 元素的方法

<template>
  <div class="home">
    <h1 ref="title"></h1>
    <button @click="changeColor"></button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    changeColor() {
      this.$refs.title.style.color = "red";
    },
  },
};
</script>

在元素上设置 ref 属性,可以在实例中通过 $refs 节点获取设置 ref 属性的 DOM 元素

如果是在组件标签上设置 ref 属性,则在 $refs 节点中获取的是这个组件实例

上次编辑于:
贡献者: ViewRoom