其他分享
首页 > 其他分享> > vue子父访问parent root

vue子父访问parent root

作者:互联网

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <comp> </comp>
    </div>

    <template id="comp">
      <div id="">
        <p>{{message}}</p>
        <button type="button" @click="parent">获取父</button>
        <button type="button" @click="root">获取根</button>
      </div>
    </template>

    <script>
      // 子组件
      const comp = Vue.extend({
        template: '#comp',
        data() {
          return {
            message: 'Hello furong!',
          }
        },
        methods: {
          // 两个均不常用
          parent() {
            console.log(this.$parent.message);
          },
          root() {
            console.log(this.$root.message);
          }
        }
      })

      // root
      const app = new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue.js!',
        },
        components: {
          comp,
        },
      })
    </script>
  </body>
</html>

标签:Vue,子父,parent,comp,app,vue,message,root
来源: https://www.cnblogs.com/zhangxuechao/p/14976567.html