Vue.js $refs用法案例详解
时间:2021-12-04 09:32:55|栏目:vue|点击: 次
尽管有 prop 和事件,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个引用 ID。
ref 为子组件指定一个引用 ID,使父组件能通过 ref 直接访问子组件中的数据
通过 this.$refs.outsideComponentRef 能直接定位到 ref=“outsideComponentRef” 的上,并返回该实例化对象
一、ref使用在外面的组件上
<div id="app">
<component-father ref="outsideComponentRef"></component-father>
</div>
<script>
var refoutsidecomponentTem = {
template: "<div class='childComp'><h5>{{test}}</h5></div>",
data(){
return{
test:'我是子组件'
}
}
};
new Vue({
el: "#app",
components: {
"component-father": refoutsidecomponentTem
},
mounted:function () {
console.log(this); // #app vue实例
console.log(this.$refs.outsideComponentRef); // VueComponent vue实例
console.log(this.$refs.outsideComponentRef.test); // '我是子组件'
}
});
</script>
二、ref使用在外面的元素上
<div id="app">
<component-father></component-father>
<p ref="outsideComponentRef">p标签</p>
</div>
<script>
var refoutsidecomponentTem = {
template: "<div class='childComp'><h5>{{test}}</h5></div>",
data(){
return{
test:'我是子组件'
}
}
};
new Vue({
el: "#app",
components: {
"component-father": refoutsidecomponentTem
},
mounted:function () {
console.log(this.$refs.outsideComponentRef); // 返回 “<p>p标签</p>”对象
}
});
</script>
栏 目:vue
下一篇:vue-cli开发时,关于ajax跨域的解决方法(推荐)
本文标题:Vue.js $refs用法案例详解
本文地址:http://www.codeinn.net/misctech/185779.html






