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 root

上一篇:0010__bat的pushd和popd


下一篇:vue组件data必须是函数