侧边栏壁纸
博主头像
前端学习

行动起来,活在当下

  • 累计撰写 307 篇文章
  • 累计创建 18 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
VUE

vue组件通信—子组件访问父组件

Administrator
2022-05-18 / 0 评论 / 0 点赞 / 87 阅读 / 0 字

根组件

// 根组件 
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;
}

代码演示:

202105271622081552963313

$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);
  }
})

代码演示:

202105271622081772829947

0
Vue

评论区