Vue 'ref' 属性


示例

使用ref属性来更改里面的文本<p>标签:

<div id="app">
  <p ref="pEl">Initial text.</p>
  <button v-on:click="changeText">Change text</button>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script type="module">
  const app = Vue.createApp({
    methods: {
      changeText(){
        this.$refs.pEl.innerHTML = "Hello!";
      }
    }
  })
  app.mount('#app')
</script>
亲自试一试 »

请参阅下面的更多示例。


定义和用法

这个ref属性用于标记元素<template>,以便可以从$refs里面有物体<script>

我们可以使用ref属性和$refsVue 中的对象作为纯 JavaScript 中方法的替代方案,例如getElementById()或者querySelector()

如果使用以下命令创建 HTML 元素v-forref属性,生成的 DOM 元素将被添加到$refs对象作为数组,如本例所示:

示例

<ul>
  <li v-for="x in liTexts" ref="liEl">{{ x }}</li>
</ul>
运行示例 »

更多示例

示例1

里面的文字是a<p>元素被改变。

<template>
  <h1>Example</h1>
  <p>Click the button to put "Hello!" as the text in the green p element.</p>
  <button @click="changeVal">Change Text</button><br>
  <p ref="pEl" id="pEl">This is the initial text</p>
</template>

<script>
  export default {
    methods: {
      changeVal() { 
        this.$refs.pEl.innerHTML = "Hello!";
      }
    }
  };
</script>

<style>
#pEl {
  background-color: lightgreen;
  display: inline-block;
}
</style>
运行示例 »

示例2

正文从第一部分开始<p>标签被复制到第二个<p>标签。

<template>
  <h1>Example</h1>
  <p ref="p1">Click the button to copy this text into the paragraph below.</p>
  <button @click="transferText">Transfer text</button>
  <p ref="p2">...</p>
</template>

<script>
  export default {
    methods: {
      transferText() { 
        this.$refs.p2.innerHTML = this.$refs.p1.innerHTML;
      }
    }
  };
</script>
运行示例 »

示例3

<p>元素获取与输入字段中写入的内容相同的内容。

<template>
  <h1>Example</h1>
  <p>Start writing inside the input element, and the text will be copied into the last paragraph by the use of the '$refs' object.</p>
  <input ref="inputEl" @input="getRefs" placeholder="Write something..">
  <p ref="pEl"></p>
</template>

<script>
  export default {
    methods: {
      getRefs() { 
        this.$refs.pEl.innerHTML = this.$refs.inputEl.value;
      }
    }
  };
</script>
运行示例 »

示例4

该按钮显示了存储为数组元素的第三个列表元素$refs目的。

<template>
  <h1>Example</h1>
  <p>Click the button to reveal the 3rd list element stored as an array element in the $refs object.</p>
  <button @click="getValue">Get the 3rd list element</button><br>
  <ul>
    <li v-for="x in liTexts" ref="liEl">{{ x }}</li>
  </ul>
  <pre>{{ thirdEl }}</pre>
</template>

<script>
  export default {
    data() {
      return {
        thirdEl: ' ',
        liTexts: ['Apple','Banana','Kiwi','Tomato','Lichi']
      }
    },
    methods: {
      getValue() { 
        this.thirdEl = this.$refs.liEl[2].innerHTML;
        console.log("this.$refs.liEl = ",this.$refs.liEl);
      }
    }
  };
</script>

<style>
pre {
  background-color: lightgreen;
  display: inline-block;
}
</style>
运行示例 »

相关页面

Vue教程:Vue 模板参考

Vue教程:Vue v-for 指令

Vue参考:Vue $refs 对象