簡體   English   中英

如何使用 vuejs 中的數據初始化應用程序

[英]How to initialise an app with data in vuejs

我正在使用一個名為 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' 實際上是一個對象,而不僅僅是一個簡單的字符串。 如果這有所作為。

我知道如何為子組件傳遞道具等,但我正在努力將主要配置數據導入頂級 Vue 應用程序!

Foo.vue:

添加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>

main.js

添加template:'<Foo :y="y"'/>到 vue 實例和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'/>" });

這就是我的做法。

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 應用程序。

雖然關於單個文件組件的文檔的重點似乎是一個單一的單頁應用程序,但這不是我所需要的。

解析度

如果您必須使用頂級 Vue 應用程序的數據,您可以使用$parent$root來實現。 然后你可以使用該 Vue 實例的$data來訪問它的數據。 這是Vue實例的文檔

使用$parent ,您將獲得一個組件父級的 Vue 實例。

this.$parent.$data.y

使用$root您將獲得當前組件樹的根 Vue 實例。

this.$root.$data.y

所以Foo.vue會是這樣的:

<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>

您可以在此處查看實時代碼。

更多的

但這不是推薦的方式。 如果要將數據傳遞給子組件,可以使用props 如果你不喜歡 props,你可以使用Vuex創建一個全局數據存儲來放置你的頂級選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM