意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

Vue中ref的简单用法是怎样,定义是什么

来源:恒创科技 编辑:恒创科技编辑部
2024-01-21 06:00:59
在实际应用中,我们有时候会遇到“Vue中ref的简单用法是怎样,定义是什么”这样的问题,我们该怎样来处理呢?下文给大家介绍了解决方法,希望这篇“Vue中ref的简单用法是怎样,定义是什么”文章能帮助大家解决问题。


     


Vue中ref的简单用法是怎样,定义是什么

ref 定义:被用来给元素或子组件注册引用信息。引用信息会被注册在父组件上的$refs对象上。

如果是在普通的dom元素上使用,引用指向的就是dom元素; 如果用在子组件上,引用指向的就是组件实例。

举例:

组件1:

<template>

  <div>

      我是{

{name}}

  </div>

</template>

<script>

export default {  

    name:'Cpn1',

    data() {

        return {

            name:'组件1'

        }

    },

}

</script>

组件2:

<template>

  <div>我是{

{name}}</div>

</template>

<script>

export default { 

    name:'Cpn2',

    data() {

        return { 

            name:'组件2'

        }

    },

}

</script>

App.vue

<template>

  <div id="app">

    <cpn-1 ref="c1"></cpn-1>

    <cpn-2 ref="c2"></cpn-2>

    <button @click="showDom">按钮</button>

    <h2 ref="title">我是标题</h2>

    <input type="text" ref="input" value="123">

  </div>

</template>

<script>

import Cpn1 from "./components/Cpn1.vue";

import Cpn2 from "./components/Cpn2.vue";

export default { 

  components: {

    Cpn1, Cpn2 },

  name: "App",

  methods: { 

    showDom() { 

      console.log(this.$refs.c1);

      console.log(this.$refs.c2.$data.name);

      console.log(this.$refs.title)

      console.log(this.$refs.input.value)

      // 获取一个真实的dom对象并修改值

      var title=this.$refs.title;

      title.innerText="helloWord"

    },

  },

};

</script>

执行上面的程序,点击页面上的《按钮》,效果如下:

同时看控制台:

可以看到当ref对象用在普通元素上时获取到的是普通DOM元素,当ref用在子组件上时,引用指向组件实例。

根据实际需要,可以通过ref给元素或者子组件注册引用信息,在需要用到的时候我们可以通过$refs获取真实的DOM元素或者组件实例进行我们想要的操作。


这篇关于“Vue中ref的简单用法是怎样,定义是什么”的文章就介绍到这了,更多相关的内容,欢迎关注恒创科技,小编将为大家输出更多高质量的实用文章!
上一篇: Node.js插件怎么使用,如何用于实现Excel的读写 下一篇: 手机怎么远程登录云服务器?