Javascript 将数据传递给 vue.js 中的组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34534151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:31:18  来源:igfitidea点击:

Passing data to components in vue.js

javascriptvue.js

提问by retrograde

I'm struggling to understand how to pass data between components in vue.js. I have read through the docs several times and looked at many vue related questions and tutorials, but I'm still not getting it.

我正在努力理解如何在 vue.js 中的组件之间传递数据。我已经多次阅读文档并查看了许多与 vue 相关的问题和教程,但我仍然没有明白。

To wrap my head around this, I am hoping for help completing a pretty simple example

为了解决这个问题,我希望帮助完成一个非常简单的例子

  1. display a list of users in one component (done)
  2. send the user data to a new component when a link is clicked (done) - see update at bottom.
  3. edit user data and send it back to original component (haven't gotten this far)
  1. 在一个组件中显示用户列表(完成)
  2. 单击链接(完成)时将用户数据发送到新组件 - 请参阅底部的更新。
  3. 编辑用户数据并将其发送回原始组件(还没有到这一步)

Here is a fiddle, which fails on step two: https://jsfiddle.net/retrogradeMT/d1a8hps0/

这是一个小提琴,在第二步失败:https: //jsfiddle.net/retrogradeMT/d1a8hps0/

I understand that I need to use props to pass data to the new component, but I'm not sure how to functionally do it. How do I bind the data to the new component?

我知道我需要使用 props 将数据传递给新组件,但我不确定如何在功能上做到这一点。如何将数据绑定到新组件?

HTML:

HTML:

    <div id="page-content">
       <router-view></router-view>
     </div>

 <template id="userBlock" >
   <ul>
     <li v-for="user in users">{{user.name}} - <a v-link="{ path: '/new' }"> Show new component</a>
     </li>
   </ul>
 </template>

  <template id="newtemp" :name ="{{user.name}}">
    <form>
      <label>Name: </label><input v-model="name">
      <input type="submit" value="Submit">
    </form>
  </template>

js for main component:

主要组件的js:

Vue.component('app-page', {
  template: '#userBlock',

  data: function() {
    return{

        users: []
      }
    },

ready: function () {
    this.fetchUsers();
},

methods: {
    fetchUsers: function(){
        var users = [
          {
            id: 1,
            name: 'tom'
          },
          {
            id: 2,
            name: 'brian'
          },
          {
            id: 3,
            name: 'sam'
          },
        ];

        this.$set('users', users);
     }
    }
  })

JS for second component:

第二个组件的JS:

Vue.component('newtemp', {
  template: '#newtemp',
  props: 'name',
  data: function() {
    return {
        name: name,
        }
   },
})

UPDATE

更新

Ok, I've got the second step figured out. Here is a new fiddle showing the progress: https://jsfiddle.net/retrogradeMT/9pffnmjp/

好的,我已经弄清楚了第二步。这是一个显示进度的新小提琴:https: //jsfiddle.net/retrogradeMT/9pffnmjp/

Because I'm using Vue-router, I don't use props to send the data to a new component. Instead, I need set params on the v-link and then use a transition hook to accept it.

因为我使用的是 Vue-router,所以我不使用 props 将数据发送到新组件。相反,我需要在 v-link 上设置参数,然后使用过渡钩子来接受它。

V-link changes see named routes in vue-router docs:

V-link 更改参见 vue-router 文档中的命名路由

<a v-link="{ name: 'new', params: { name: user.name }}"> Show new component</a>

Then on the component, add data to the route options see transition hooks:

然后在组件上,将数据添加到路由选项中,参见 transition hooks

Vue.component('newtemp', {
  template: '#newtemp',
  route: {
   data: function(transition) {
        transition.next({
            // saving the id which is passed in url
            name: transition.to.params.name
        });
     }
  },
 data: function() {
    return {
        name:name,
        }
   },
})

采纳答案by notANerdDev

-------------Following is applicable only to Vue 1 --------------

-------------以下仅适用于 Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.

可以通过多种方式传递数据。该方法取决于使用类型。



If you want to pass data from your html while you add a new component. That is done using props.

如果要在添加新组件时从 html 传递数据。这是使用道具完成的。

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-nameto your propsattribute.

仅当您将道具名称添加prop-nameprops属性时,此道具值才可用于您的组件。



When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

当数据由于某些动态或静态事件而从一个组件传递到另一个组件时。这是通过使用事件调度器和广播器来完成的。例如,如果您有这样的组件结构:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A>to <my-child-B>then in <my-child-A>you will have to dispatch an event:

并且您想从 to 发送数据<my-child-A><my-child-B>然后在<my-child-A>您必须调度一个事件:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B>you broadcast the event along with the data. So in the parent:

此事件将一直沿父链向上传播。并且从您有分支的任何父级向<my-child-B>您广播事件和数据。所以在父级中:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B>we will add another event:

现在这个广播将沿着子链传播。无论您想在哪个孩子上获取事件,在我们的例子中,<my-child-B>我们都会添加另一个事件:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},


The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.

第三种传递数据的方式是通过 v-links 中的参数。当组件链完全销毁或 URI 更改时使用此方法。我可以看到你已经理解他们了。



Decide what type of data communication you want, and choose appropriately.

Decide what type of data communication you want, and choose appropriately.

回答by acdcjunior

The best way to send data from a parent component to a child is using props.

从父组件向子组件发送数据的最佳方式是使用props

Passing data from parent to child via props

将数据从父级传递给子级 props

  • Declare props(array or object) in the child
  • Pass it to the child via <child :name="variableOnParent">
  • 在孩子中声明props(数组或对象
  • 通过它传递给孩子 <child :name="variableOnParent">

See demo below:

请参阅下面的演示:

Vue.component('child-comp', {
  props: ['message'], // declare the props
  template: '<p>At child-comp, using props in the template: {{ message }}</p>',
  mounted: function () {
    console.log('The props are also available in JS:', this.message);
  }
})

new Vue({
  el: '#app',
  data: {
    variableAtParent: 'DATA FROM PARENT!'
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <p>At Parent: {{ variableAtParent }}</p>
  <child-comp :message="variableAtParent"></child-comp>
</div>

回答by Jeff

I think the issue is here:

我认为问题出在这里:

<template id="newtemp" :name ="{{user.name}}">

When you prefix the prop with :you are indicating to Vue that it is a variable, not a string. So you don't need the {{}}around user.name. Try:

当你给 prop 加上前缀时,:你就向 Vue 表明它是一个变量,而不是一个字符串。所以你不需要{{}}around user.name。尝试:

<template id="newtemp" :name ="user.name">

EDIT-----

编辑 - - -

The above is true, but the bigger issue here is that when you change the URL and go to a new route, the original component disappears. In order to have the second component edit the parent data, the second component would need to be a child component of the first one, or just a part of the same component.

上面是正确的,但这里更大的问题是,当您更改 URL 并转到新路由时,原始组件消失了。为了让第二个组件编辑父数据,第二个组件需要是第一个组件的子组件,或者只是同一组件的一部分。

回答by Lucas Serena

I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.

我找到了一种在 Vue 中将父数据传递到组件范围的方法,我认为这有点麻烦,但也许这会对您有所帮助。

1) Reference data in Vue Instance as an external object (data : dataObj)

1)将Vue Instance中的数据作为外部对象引用 (data : dataObj)

2) Then in the data return function in the child component just return parentScope = dataObjand voila. Now you cann do things like {{ parentScope.prop }}and will work like a charm.

2)然后在子组件中的数据返回函数中返回parentScope = dataObj并瞧。现在你可以做这样的事情,{{ parentScope.prop }}并且会像魅力一样工作。

Good Luck!

祝你好运!

回答by T.Todua

I access main properties using $root.

我使用$root.

Vue.component("example", { 
    template: `<div>$root.message</div>`
});
...
<example></example>

回答by Kjelle J

A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.

一个全局的 JS 变量(对象)可以用来在组件之间传递数据。示例:将数据从 Ammlogin.vue 传递到 Options.vue。在 Ammlogin.vue 中,rspData 设置为来自服务器的响应。在 Options.vue 中,来自服务器的响应通过 rspData 提供。

index.html:

索引.html:

<script>
    var rspData; // global - transfer data between components
</script>

Ammlogin.vue:

Ammlogin.vue:

....    
export default {
data: function() {return vueData}, 
methods: {
    login: function(event){
        event.preventDefault(); // otherwise the page is submitted...
        vueData.errortxt = "";
        axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
            .then(function (response) {
                vueData.user = '';
                vueData.password = '';
                // activate v-link via JS click...
                // JSON.parse is not needed because it is already an object
                if (response.data.result === "ok") {
                    rspData = response.data; // set global rspData
                    document.getElementById("loginid").click();
                } else {
                    vueData.errortxt = "Felaktig av?ndare eller l?senord!"
                }
            })
            .catch(function (error) {
                // Wu oh! Something went wrong
                vueData.errortxt = error.message;
            });
    },
....

Options.vue:

选项.vue:

<template>
<main-layout>
  <p>Alternativ</p>
  <p>Resultat: {{rspData.result}}</p>
  <p>Meddelande: {{rspData.data}}</p>
  <v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
 import MainLayout from '../layouts/Main.vue'
 import VLink from '../components/VLink.vue'
 var optData = { rspData: rspData}; // rspData is global
 export default {
   data: function() {return optData},
   components: {
     MainLayout,
     VLink
   }
 }
</script>