代码之家  ›  专栏  ›  技术社区  ›  artfulrobot

如何使用vuejs中的数据初始化应用程序

  •  2
  • artfulrobot  · 技术社区  · 6 年前

    我使用一个名为Foo的文件组件:

    <template>
    <div>
      This is the app. X  is {{ x }}, y is {{ y }}
    </div>
    </template>
    <script>
    export default {
      data() {
       return { x: 'hello x' };
      },
    }
    </script>
    

    // somewhere here 'node' gets set to a DOM node,
    // and 'y' is created.
    import Vue from 'vue';
    import Foo from './Foo.vue';
    const app = new Vue({             
      'el': node,                     
      data: {y},
      render: h => h(Foo)             
    });                               
    

    这太简单了,因为“y”实际上是一个对象,而不仅仅是一个简单的字符串。如果这有什么不同的话。

    我知道如何传递道具等 子组件

    3 回复  |  直到 6 年前
        1
  •  1
  •   Boussadjra Brahim    6 年前

    足球俱乐部:

    添加 props:['y']

    <template>
    <div>
      This is the app. X  is {{ x }}, y is {{ y }}
    </div>
    </template>
    <script>
      export default {
      props:['y']
        data() {
          return {
            x: 'hello x'
          };
        },
      }
    </script>
    

    主.js

    添加 template:'<Foo :y="y"'/> node 应该是有效的html元素

    // somewhere here 'node' gets set to a DOM node,
    // and 'y' is created.
    import Vue from 'vue';
    import Foo from './Foo.vue';
    const app = new Vue({
      'el': node,
      data: {
        y: "some content"
      },
      template: "<Foo :y='y'/>"
    });
        2
  •  1
  •   artfulrobot    6 年前

    我是这样做的。

    Foo.vue 添加 props

    <template>
    <div>
      This is the app. X  is {{ x }}, y is {{ y }}
    </div>
    </template>
    <script>
    export default {
      data() {return { x: 'hello x' };},
      props: [ 'y' ],
    }
    </script>
    

    然后在创建应用程序的主js中:

    // somewhere here 'node' gets set to a DOM node,
    // and 'y' is created.
    import Vue from 'vue';
    import Foo from './Foo.vue';
    const app = new Vue({             
      'el': node,
      render: h => h(Foo, {props: {y})
    });                               
    

    这样y就可以作为道具传入,但不用使用 template 这需要包含Vue编译的更重的编译器。

    这样做的好处是,我的CMS可以打印出页面的块,每个都应该是Vue应用程序,可以包含每个应用程序的配置,并且可以创建所有只在内容上有所不同的Vue应用程序。

    虽然单文件组件的文档重点似乎是一个单一页面的应用程序,但这不是我需要的。

        3
  •  0
  •   Miaonster    6 年前

    $parent $root . 然后你可以使用 $data document Vue实例的。

    您将获得一个组件的父级的Vue实例。

    this.$parent.$data.y
    

    $根 您将获得当前组件树的根Vue实例。

    this.$root.$data.y
    

    所以 会是这样的:

    <template>
      <div>This is the app. X is {{ x }}, y is {{ y }}</div>
    </template>
    
    <script>
    export default {
      data: function() {
        return { x: "x" };
      },
      computed: {
        y: function() {
          return this.$parent.$data.y;
        }
      }
    };
    </script>
    

    here

    更多

    但这不是推荐的方法。如果要将数据传递给子组件,可以使用 props Vuex 创建一个全局数据存储,将顶级选项放在哪里。