[英]How do I pass data from Vue Instance to a Single File Component
I've been working with Vue for sometime, but I've never really tried working with Single File Components alongside webpack. 我已经使用Vue已有一段时间了,但是我从未真正尝试过将单个文件组件与webpack一起使用。 Here's the problem I'm having.
这是我遇到的问题。 I have 2 files: main.js (which contains the Vue root instance) and App.vue (which is a single file component. The code in each file goes as thus:
我有2个文件:main.js(包含Vue根实例)和App.vue(单个文件组件。每个文件中的代码如下:
main.js: main.js:
import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', components: { App, }, data(){ return { greeting: "Hello World!", } }, render: h => h(App), });
App.vue: App.vue:
<template> <div id="app"> {{greeting}} </div> </template> <script> export default { name: 'App', } </script>
Please note that I'm using webpack, and the main.js file is meant to be an entry point. 请注意,我使用的是webpack,main.js文件旨在作为入口点。 The code is bundled to a file called bundle.js.
该代码捆绑到一个名为bundle.js的文件中。
Now, my problem is that, when the template in App.vue renders, it doesn't show "Hello Word", which is the value of {{greeting}}. 现在,我的问题是,当App.vue中的模板呈现时,它不会显示“ Hello Word”,这是{{greeting}}的值。 I expect that data passed from the root Vue instance in main.js should be available to the App.vue component.
我希望从main.js中的根Vue实例传递来的数据应可用于App.vue组件。
The {{greeting}} isn't evaluated when I put it in my index.html file, which links to bundle.js (the bundled version of main.js) 当我将{{greeting}}放入index.html文件时,该文件不会进行评估,该文件链接到bundle.js(main.js的捆绑版)
index.html: index.html的:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Nothing</title> <script src="/dist/build.js"></script> </head> <body> <div id="app"></div> {{greeting}} </body> </html>
Does this mean that data in the root vue instance isn't available anywhere? 这是否意味着根vue实例中的数据在任何地方都不可用? What should I do?
我该怎么办?
The greeting
needs to be in your component's data
. greeting
必须在您组件的data
。 This has nothing to do with SFC (Single File Components), it's just the way Vue's templates work: they read from the component's data. 这与SFC(单个文件组件)无关,这只是Vue模板的工作方式:它们从组件的数据中读取。
So what you need to do is move the data
to the appropriate component, which is tied with the template where you're trying to use. 因此,您需要做的是将
data
移动到适当的组件,该组件与您要使用的模板相关联。
<template>
<div id="app">
{{ greeting }}
</div>
</template>
<script>
export default {
name: 'App',
data () {
return { greeting: 'Hello World!', }
},
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.