ref 与 refs 在Vue2.0与3.0 中的使用

267 阅读1分钟

ref/$refs Vue中组建通信的方式之一 Vue不同版本中使用方式不同

Vue 3.0 中的使用

// 获取组建对象
<h3 ref="hello">我是一个H3 元素</h3>

// 需要使用refs 转义
 const hello = ref(null)
 // 在自定义事件中
 // hello.value 即为H3 标签对象 这里输出的是标签文本
 console.log(hello.value.innerHTML)
 
 // 获取当前组建子组件的数据 调用子组件的方法
 // 在子组件中定义数据
  const data = reactive({
         list:['1','2','3'],
          msg:"乌索普.......",
          titles:"索隆"
  })
  
  // 在父组建声明中定义 ref 对象
  <testSubVue ref="oks"></testSubVue>
  
  // 同样需要使用ref 转义
  const oks = ref(null)
  
  // 在自定义方法中  获取子组件的msg 数据
  console.log(oks.value.msg)
  
  // 调用子组件的方法  在子组件中定义open 方法  父组件中直接调用
  oks.value.open()

Vue 2.0 中的使用

//给当前组建内部标签绑定ref 属性
<span ref="hello">小明的爸爸有100元</span>

// vue 2.0中不需要转义直接使用$ref 获取到定义对象 hello
this.$refs.hello  // 直接获取到当前元素标签

// ref 获取input 输入框的值
<input type="text" ref="input">

// 在自定义事件中输出input 输入框的值
this.$refs.input.value

// 获取当前组建子组建中的data 与方法
<testView ref="hello" ></testView>
// 子组件中定义的data
    data() {
        return{
          name:"蒙奇D 路飞",
          list:["A","B","C"]
       }
     },
 // 获取到子组件的中的list 数据 
this.$refs.hello.list

// 调用子组件的自定义方法 open方法
this.$refs.hello.open()

  • ref 在 Vue2.0与 3.0 中对应的使用方式记录完毕但是有一点不得不说 nextTick()
  • ref 与$refs 方法不是响应式的 必须要在模板加载完成之后才能执行 所以很多时候会配合nextTic()使用 // nextTick()
// 在自定义方法中实现
    testClick:function(){
          data.msg = "修改后的值";
          this.$nextTick(function(){
            console.log(this.$refs.hello.innerText); //输出:修改后的值
          });
       }

注意: ref 只获取节点或组建实例的属性或者方法 不会改变其属性