$parent 官方介绍: 当前组件树的根 Vue 实例。如果当前实例没有父实例,此实例将会是其自己。 既然可以获取到组件的实例,那么就可以调用组件的属性或是方法进行操作
$parent表示父组件的实例,该属性只读
下面是一个简易实例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="example">
<parent-component></parent-component>
</div>
<template id="parent-component">
<div class="parent">
<h3>我是父组件</h3>
<input v-model="parentMsg">
<p>{{parentMsg}}</p>
<child-component></child-component>
</div>
</template>
<template id="child-component">
<div class="child">
<h3>我是子组件</h3>
<p>{{msg}}</p>
<button v-on:click="showData">显示父组件数据</button>
</div>
</template>
</body>
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js" type="text/javascript"></script>
<script>
// 注册
Vue.component('parent-component', {
template: '#parent-component',
data(){
return{
parentMsg:'我是父组件的数据'
}
},
components:{
'child-component':{
template:'#child-component',
data(){
return{
msg:''
}
},
methods:{
showData(){
this.msg = this.$parent.parentMsg;
}
}
}
}
})
// 创建根实例
new Vue({
el: '#example'
})
</script>
</html>
原文链接:https://www.qiquanji.com/post/8022.html
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
微信扫码关注
更新实时通知
