vue组件通信—子组件访问父组件
根组件
// 根组件
let vm = new Vue({
el: '#app',
data: {
msg: 'hello'
},
methods: {
say() {
return 'hi ' + this.msg
}
},
computed: {
username() {
return '<span style="color:red;">' + this.msg + '</span>'
}
}
})
视图层:
<div id="app">
<child></child>
<my-list></my-list>
</div> <template id="child">
<div style="width: 200px;border:1px dashed red;text-align: center;margin: 0 auto;">
<p>child子组件</p>
<p>{{cmsg}}</p>
<p>{{csay}}</p>
<p v-html="cname"></p>
</div>
</template>
子组件:
$parent访问父组件
created: function () {
this.cmsg = this.$parent.msg;
this.csay = this.$parent.say();
this.cname = this.$parent.username;
}
代码演示:
$root访问父组件
created:
function () {
// 访问父组件
console.log(this.$root);
// 访问父组件数据中心
console.log(this.$root.msg);
// 访问父组件方法中心
console.log(this.$root.say());
// 访问父组件计算属性
console.log(this.$root.username);
// 访问父组件的根节点
console.log(this.$root.$el);
// 访问父组件属性名和值
console.log(this.$root.$attrs);
}
})
代码演示:
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果