访问元素和组件:$root 访问根实例、$parent 父组件、ref 子组件
这里介绍的方法可以访问(获取、修改)到根实例、父组件、子组件里面的数据。因为使用这些方法,可能造成难以排查到数据在哪里修改,所以慎用这些方法。1. 访问根实例: $root这里创建一个根实例 new Vue({el:"#app",data: {foo: 1},computed: {bar: function () { /* ... */...
·
这里介绍的方法可以访问(获取、修改)到根实例、父组件、子组件里面的数据。因为使用这些方法,可能造成难以排查到数据在哪里修改,所以慎用这些方法。
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
一起使用的时候,你得到的引用将会是一个包含了对应数据源的这些子组件的数组
更多推荐
已为社区贡献23条内容
所有评论(0)