访问元素和组件:$root 访问根实例、$parent 父组件、ref 子组件

这里介绍的方法可以访问(获取、修改)到根实例、父组件、子组件里面的数据。因为使用这些方法,可能造成难以排查到数据在哪里修改,所以慎用这些方法。

1. 访问根实例: $root

这里创建一个根实例 

new Vue({
  el:"#app",
  data: {
    foo: 1
  },
  computed: {
    bar: function () { /* ... */ }
  },
  methods: {
    baz: function () { /* ... */ }
  }
})

 使用 $root 可以访问/ 根实例的数据访问/ 调用根实例的方法

// 获取根组件的数据
this.$root.foo

// 写入根组件的数据
this.$root.foo = 2

// 访问根组件的计算属性
this.$root.bar

// 调用根组件的方法
this.$root.baz()

2.  访问父级组件实例:$parent

Vue.component('parent',{
	props:["parent-prop"]
	template:` ...`
	})
	
Vue.component('child',{
	template:` ...`
	})
<parent>
	<child>
	</child>
</parent>

使用 $parent 可以访问/ 根实例的数据访问/ 调用根实例的方法

// 获取父组件的数据
Vue.component('child',{
    data:{return parentdata:this.$parent.parentporp}
	template:` ...`
	})

3. 访问子组件实例或子元素: ref 特性:给子组件添加 ID

1. 不唯一,可以多个子组件设定相同的 ref 值)

2. 父组件通过 refs 访问子组件/子元素

<parent>
	<child ref="the-child">
	</child>
</parent>

a .可以在父组件 parent 里面使用 this.refs.the-child 来访问子组件里面的数据/ 方法

b. 可以访问父组件里面子元素(不是组件,是父组件中的dom 元素)的数据/ 方法

甚至可以通过其父级组件定义方法: 

methods: {
  // 用来从父级组件聚焦输入框
  focus: function () {
    this.$refs.input.focus()
  }
}

 这样就允许父级组件通过下面的代码聚焦 <base-input> 里的输入框:

this.$refs.usernameInput.focus()

另一个例子:(访问父组件里面子元素的数据

在子组件:这个例子是给 "welcome"  这个组件设置了一个this.$refs.input.mes

在根实例:this.$refs.input.mes 可以访问到子组件的 data 数据。这里访问到了子组件的 "mes" 数据

<div id="div">
   <form>
   <input is="welcome" ref="input" >
   </input>
   </form>
</div>
Vue.component("welcome",{
  template:`<form><input>点击通过emit( )触发事件</input></form>`,
  data:function(){
    return {mes:"good good study"}}
})
 
new Vue({
  el:"#div",
  mounted:
    function(){
      alert(this.$refs.input.mes) 
   }
  })

网页渲染效果: 

c. 不唯一,可以多个子组件设定相同的 ref 值)

当 ref 和 v-for 一起使用的时候,你得到的引用将会是一个包含了对应数据源的这些子组件的数组

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值