简体   繁体   English

如何使用单个文件组件传递道具?

[英]How Do I Pass Props Using Single File Components?

Coming to Vue from React. 来自React的Vue。 For the most part there are a lot of similarities but passing props seems a little different. 在大多数情况下有很多相似之处,但传递props似乎有点不同。 I couldn't find much documentation on how to do this using single file components. 我找不到很多关于如何使用单个文件组件执行此操作的文档。 I import all my data for the app in main.js . 我在main.js导入了应用程序的所有数据。 I'm wondering how I can get parts of my data like currentUser for example, to ResourceInfo.vue ? 我想知道如何获取我的数据的一部分,例如currentUser ,如ResourceInfo.vue Again assuming these are all single file components. 再假设这些都是单个文件组件。 Do I need to pass it down through the <App/> part under main.js template option, then into <resource-info></resource-info> in App.vue then somehow into ResourceInfo.vue ? 我需要它向下传递通过<App/>下部分main.js模板选项,然后进入<resource-info></resource-info>App.vue然后以某种方式进入ResourceInfo.vue I'd like to stay away from having to learn Vuex as well because I'm just starting out. 我也不想学习Vuex,因为我刚开始学习。 Thanks! 谢谢!

main.js main.js

import Vue from 'vue'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();

/* eslint-disable no-new */
var vm = new Vue({
  el: '#app',
  data: function() {
    return {
        users: {},
        currentUser: {},
        quizzes: {},
        resources: []
    }
  },
  template: '<App/>',
  components: { App, ResourceInfo },
})

App.vue App.vue

<template>
  <div id="app">
    <navbar></navbar>
    <resource-info></resource-info>
  </div>
</template>

<script>
import Navbar from './components/Navbar'
import ResourceInfo from './components/ResourceInfo'

export default {
  name: 'app',
  components: {
    Navbar,
    ResourceInfo
  }
}
</script>

<style>
</style>

ResourceInfo.vue ResourceInfo.vue

<template>
</template>

<script>
var resourcesRef = firebase.database().ref('resources');

module.exports = {
  name: 'resource-info',
  data: function() {
    return {
      header: 'Before you build your quiz we just need some quick info.',
      resource: {
        type: '',
        title: '',
        url: '',
        desc: '',
        timesPassed: 0
      },
    }
  },
  firebase: {
    resources: resourcesRef
  },
  methods: {
    saveToFirebase: function() {
      resources.push({
        resource: this.resource
      })

      // Clear inputs  

      this.resource.title = '',
      this.resource.type = '',
      this.resource.desc = '',
      this.resource.url = ''

      console.log("Saving resource data...")

    }
  }
}
</script>

<style>
</style>

@DanM. @DanM。 has already provided the answer, and I hope you managed to fix your props as per his guidance. 已经提供了答案,我希望你能按照他的指导设法修复你的props

I am writing this answer so I can share my method of dealing with currentUser in my app (only for logged-in users). 我正在写这个答案,所以我可以在我的应用程序中分享我处理currentUser方法(仅限登录用户)。 Here is my project structure (highly simplified for this answer): 这是我的项目结构(这个答案高度简化):

Template: webpack, installed using vue init webpack my-project using vue-cli 模板:webpack,使用vue-cli使用vue init webpack my-project安装

My app files: 我的app文件:

  • ./main.js : app entry file ./main.js:app条目文件
  • ./App.vue : responsible for page layout, like header, footer, and route contents using router-view ./App.vue :使用router-view负责页面布局,如页眉,页脚和路径内容
  • ./components/ : Common components like navbar, footer, etc. ./components/ :常用组件,如导航栏,页脚等。
  • ./routes/ : Route components. ./routes/ :路由组件。 I prefer to put it here instead of cluttering my components folder. 我更喜欢把它放在这里而不是混乱我的组件文件夹。
  • and a lot more... 还有更多......

Code in my main.js : Just the standard code to define routes and bootstrap the app. 我的main.js的代码:只是用于定义路由和引导应用程序的标准代码。 Nothing special here. 这里没什么特别的。

Code in my App.vue - here is where currentUser gets fetched. 我的App.vue代码 - 这里是获取currentUser地方。 Navbar also gets inserted, where I pass currentUser via props Navbar也会插入,我通过props传递currentUser

<template>
    <div class="app-container">
        <app-navbar :currentUser="currentUserInfo"></app-navbar>
        <router-view></router-view>
        <app-footer></app-footer>
    </div>
</template>
<script>
import AppNavbar from "./components/app-navbar.vue"
import AppFooter from "./components/app-footer.vue"

export default {
    components: {
        "app-navbar": AppNavbar
    },
    data: function() {
        return {
            currentUserInfo: {
                loading: true
            } // start with an empty object and modify later
        }
    },
    // ... all other code ...
    created: function() {
        // Ensure that this is a logged-in user. Or else redirect to login page
        this.$http.get("/api/currentUser").then(response => {
            // process response
            this.currentUserInfo = response
            this.currentUserInfo.loading = false
        }, error => {
            // user not found. exit the Vue app and go to login page (directly from server)
            // Refer to my other answer: http://stackoverflow.com/a/40194152/654825

            // Or alternatively, you can serve your App's index.html only for logged-in users. Then you will never reach here.
        })
    },
    // ... more code ...
}
</script>

Now receive currentUser in your component ./components/navbar.vue as follows: 现在在组件./components/navbar.vue中接收currentUser ,如下所示:

<template>
    <div class="navbar">
        <!-- some code - branding, etc.. -->
        <div>{{currentUser.loading ? "Loading..." : currentUser.name}}</div>
        <!-- some more code - logout link, etc.. -->
    </div>
</template>
<script>
export default {
    props: ["currentUser"],
    // and more ...
}
</script>

Thats a lot to digest. 这很难消化。 I also use vuex extensively, which I did not show in the sample above as you did not want vuex . 我也广泛使用vuex ,我没有在上面的示例中显示,因为你不想要vuex

I hope it helps to structure your app. 我希望它有助于构建您的应用程序。

There are a couple of ways you can achieve this. 有几种方法可以实现这一目标。

Method #1 - using 'template' 方法#1 - 使用'模板'

If you want to pass props down from main.js , you need to edit the template there and pass the data down to App first: 如果你想从main.js传递道具,你需要在那里编辑模板并首先将数据传递给App

main.js main.js

new Vue({
  ...
  template: '<App :current-user="currentUser"/>'
  ...
})

...and in App.vue ......并在App.vue中

<template>
  <div id="app">
    <navbar></navbar>
    <resource-info :current-user="currentUser"></resource-info>
  </div>
</template>

<script>
module.exports = {
  ...
  props: ['current-user']
  ...
}
</script>
...

Then, currentUser will be available in ResourceInfo.vue (remember to add props: ['current-user'] ). 然后, currentUser将在ResourceInfo.vue中可用(记得添加props: ['current-user'] )。

Method #2 - passing down via 'render' attrs 方法#2 - 通过'render'attrs向下传递

Render blocks allow defining attributes on the component you're rendering. 渲染块允许在要渲染的组件上定义属性。

In your case, currentUser can be passed down like so: 在您的情况下, currentUser可以像这样传递:

var vm = new Vue({ 
    el: '#app', 
    data: function() { 
        return { 
            users: {}, 
            currentUser: {}, 
            quizzes: {}, 
            resources: [] 
        }
    }, 
    render (h) { 
        return ( 
            '<App />', 
            { attrs: { currentUser } } 
        ) 
    }, 
    components: { App, ResourceInfo } 
})

Then in App.vue you'll be able to access currentUser via props: 然后在App.vue您将能够通过props访问currentUser

import Navbar from './components/Navbar'
import ResourceInfo from './components/ResourceInfo'

export default {
  name: 'app',
  props: ['current-user']
  components: {
    Navbar,
    ResourceInfo
  }
}

Now you can pass it further down to ResourceInfo.vue as you'd normally would (see below). 现在你可以像往常一样将它传递给ResourceInfo.vue (见下文)。


Passing props in general 一般传递道具

App.vue : App.vue

<template>
  <div id="app">
    <navbar></navbar>
    <resource-info :current-user="currentUser"></resource-info>
  </div>
</template>
...

And add props in ResourceInfo.vue , like so: 并在ResourceInfo.vue中添加props ,如下所示:

<template>
  <pre>{{currentUser}} <!-- dumb example --></pre>
</template>

<script>
var resourcesRef = firebase.database().ref('resources');

module.exports = {
  name: 'resource-info',
  props: ['current-user'], // You can also do prop validation here
    ...
  }
}
</script>

...

You can read more about props here :-) 你可以在这里阅读更多关于道具的信息 :-)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用道具在组件之间传递数据 - how do i pass data among components using props 如何通过vue-router和单个文件组件传递道具 - How to pass props with vue-router and Single File Components 如何使用 TypeScript 传递组件传播道具? - How do I pass down components spread props with TypeScript? Next.js 使用 getServerSideProps 如何将道具从页面传递到组件? - Next.js using getServerSideProps how do i pass props from page to components? 如何在单个组件中渲染多个道具,然后将这些道具传递给 React 中的子组件 - How do i render multiple props in a single component and then pass those props to a child component in React 如何将复杂的样式(即样式表)传递给React组件作为道具? - How do I pass complex styles (i.e. stylesheets) to React components as props? 我如何通过图像对象数组将道具传递给样式化组件和 map - how do i pass props to styled components and map through array of image objects 如何使用 Vue2 中的 Props 将数据传递给组件? - How do I pass data to a component using Props in Vue2? 如何使用 useState 将映射的道具传递给组件? - How do I pass mapped props to a component using useState? 如何将道具传递给样式组件 - how to pass props to styled components
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM