简体   繁体   English

如何在 Vue Js 中将数据值从一个组件更改为另一个组件?

[英]How can I change data value from one component to another component in Vue Js?

I am new in Vue Js.我是 Vue Js 的新手。 So, I am facing a problem to changes data value from another component.因此,我面临从另一个组件更改数据值的问题。

I have a component A:我有一个组件A:

<template>
   <div id="app">
      <p v-on:click="test ()">Something</p>
   </div>
</template>

import B from '../components/B.vue';
export default {
    components: {
        B
    },
    methods: {
        test: function() {
            B.data().myData = 124
            B.data().isActive = true
            console.log(B.data().myData);
            console.log(B.data().isActive);
        }
    }
}

Component B: B组份:

export default {
    data() {
        return {
            myData: 123,
            isActive: false

        }
    }

}

It still component B data.它仍然是 B 组份数据。 But it cannot be affected component B data.但它不会受到 B 组份数据的影响。 I want to data changes of component B from component A. How can I do that?我想从组件 A 中获取组件 B 的数据更改。我该怎么做?

Please explain me in details.请详细解释我。 I have seen vue js props attribute but I don't understand.我看过 vue js props 属性,但我不明白。

You're looking for Vuex .您正在寻找Vuex

It's the centralized store for all the data in your applications.它是应用程序中所有数据的集中存储。

Take a look at their documentation, it should be pretty straightforward.看看他们的文档,应该很简单。

You can pass down props to the component B. These props can be updated by the parent component.您可以将 props 传递给组件 B。这些 props 可以由父组件更新。 You can think of B as a stupid component that just renders what the parent tells it to rendern.您可以将 B 视为一个愚蠢的组件,它只渲染父级告诉它渲染的内容。 Example:例子:

// Component A
<template>
   <div id="app">
      <p v-on:click="test ()">Something</p>
      <b data="myData" isActive="myIsActive"></b>
   </div>
</template>

<script>
import B from '../components/B.vue';
export default {
  components: {
    B
  },
  data() {
    return {
      myData: 0,
      myIsActive: false,
    };
  },
  methods: {
    test: function() {
      this.myData = 123
      this.myIsActive = true
    }
  }
}
</script>

// Component B
<template>
  <div>{{ data }}{{ isActive }}</div>
</template>

<script>
export default {
  props: {
    data: Number,
    isActive: Boolean
};
</script>

There are few ways...有几种方法...

  1. if your components have a parent child relationship you can pass data values from parent into child.如果您的组件具有父子关系,您可以将数据值从父级传递给子级。

  2. If your want to communicate back to parent component when child component has changed something, you can use vuejs event emitter(custom event) to emit a event when data value change and that event can be listened in another component and do what you want.如果您想在子组件发生更改时与父组件进行通信,您可以使用 vuejs 事件发射器(自定义事件)在数据值更改时发出事件,并且可以在另一个组件中侦听该事件并执行您想要的操作。

  3. If your components doesn't have a relationship, then you have to use use something else than above things.如果您的组件没有关系,那么您必须使用除上述内容之外的其他内容。 You can use two things.one is event bus, other one is state management library.for vue there is a official state management library called VueX.it is very easy to use.if you want to use something else than vuex, you can use it such as redux, mobx etc.你可以用两个东西。一个是事件总线,另一个是状态管理库。对于vue,有一个官方的状态管理库叫VueX。它非常好用。如果你想使用vuex以外的东西,你可以使用它例如redux,mobx等。

This documentation has everything what you want to know.本文档包含您想知道的一切。 I don't want to put any code, because of doc is very clear.我不想放任何代码,因为文档很清楚。

VueX is the most preferable way to do this! VueX 是最好的方法! Very easy to use..非常好用。。

https://v2.vuejs.org/v2/guide/components.html https://v2.vuejs.org/v2/guide/components.html

 //component A Vue.component('my-button', { props: ['title'], template: `<button v-on:click="$emit('add-value')">{{title}}</button>` }); Vue.component('my-viewer', { props: ['counter'], template: `<button>{{counter}}</button>` }); new Vue({ el: '#app', data: { counter: 0, }, methods: { doSomething: function() { this.counter++; } } }) Vue.component('blog-post', { props: ['title'], template: '<h3>{{ title }}</h3>' }); //parent new Vue({ el: '#blog-post-demo', data: { posts: [{ id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' } ] } }); Vue.component('blog-post2', { props: ['post'], template: ` <div class="blog-post"> <h3>{{ post.title }}</h3> <button v-on:click="$emit('enlarge-text')"> Enlarge text </button> <div v-html="post.content"></div> </div>` }) new Vue({ el: '#blog-posts-events-demo', data: { posts: [{ id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' } ], postFontSize: 1 }, methods: { onEnlargeText: function() { this.postFontSize++; } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <p>Two components adding & viewing value</p> <div id="app"> <my-button :title="'Add Value'" v-on:add-value="doSomething"></my-button> <my-viewer :counter="counter"></my-viewer> </div> <br> <br> <p>Passing Data to Child Components with Props (Parent to Child)</p> <div id="blog-post-demo"> <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:title="post.title"></blog-post> </div> <p>Listening to Child Components Events (Child to Parent)</p> <div id="blog-posts-events-demo"> <div :style="{ fontSize: postFontSize + 'em' }"> <blog-post2 v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:enlarge-text="onEnlargeText"></blog-post2> </div> </div>

First, you need a parent so two component can communicate.首先,您需要一个父组件,以便两个组件可以通信。 when my-button component is clicked triggers an event add-value that calls doSomething() function, then updates the value & show it to my-viewer component.当单击my-button组件时,会触发一个调用doSomething()函数的事件add-value ,然后更新该值并将其显示给my-viewer组件。

HTML HTML

     <!--PARENT-->
     <div id="app"> 
          <!--CHILD COMPONENTS-->
          <my-button :title="'Add Value'" v-on:add-value="doSomething"></my-button>
          <my-viewer :counter="counter"></my-viewer>
     </div>

VUE.JS Vue.JS

     //component A
     Vue.component('my-button',{
         props:['title'],
         template:`<button v-on:click="$emit('add-value')">{{title}}</button>`
     });

     //Component B
     Vue.component('my-viewer',{
        props:['counter'],
        template:`<button>{{counter}}</button>`
     });

     //Parent
     new Vue({
         el: '#app',
         data:{
            counter:0,
         },
         methods:{
             doSomething:function(){
               this.counter++;
             }
        }
     })

This is base on Vue Components Guide这是基于Vue 组件指南

Passing Data to Child Components with Props (Parent to Child)使用道具将数据传递给子组件(父子组件)

VUE.JS Vue.JS

         //component (child)
         //Vue component must come first, else it won't work
         Vue.component('blog-post', {
             /*Props are custom attributes you can register on a component. When a 
               value is passed to a prop attribute, it becomes a property on that 
               component instance*/
             props: ['title'],
             template: '<h3>{{ title }}</h3>'
         });

         //parent
         new Vue({
            el: '#blog-post-demo',
            data: {
              posts: [
                 { id: 1, title: 'My journey with Vue' },
                 { id: 2, title: 'Blogging with Vue' },
                 { id: 3, title: 'Why Vue is so fun' }
              ]
            }
         });

HTML: HTML:

v-for will loop on posts and pass data to blog-post component v-for将在帖子上循环并将数据传递给blog-post组件

         <div id="blog-post-demo">
             <blog-post  v-for="post in posts"
                         v-bind:key="post.id"
                         v-bind:title="post.title"></blog-post>
         </div>

Listening to Child Components Events (Child to Parent)监听子组件事件(子到父)

HTML HTML

You must first register the event by v-on:enlarge-text="onEnlargeText" to use $emit and make sure that it's always set to lower case or it won't work properly.您必须首先通过v-on:enlarge-text="onEnlargeText"注册事件才能使用$emit并确保它始终设置为小写,否则它将无法正常工作。 example enlargeText and Enlargetext will always be converted to enlargetext , thus use enlarge-text instead, because its easy to read & valid, for a brief explanation about $emit you can read it here示例enlargeText文本和Enlargetext文本将始终转换为enlargetext文本,因此请改用放大文本,因为它易于阅读且有效,有关$emit的简要说明,您可以在此处阅读

         <div id="blog-posts-events-demo">
            <div :style="{ fontSize: postFontSize + 'em' }">
                 <blog-post
                          v-for="post in posts"
                          v-bind:key="post.id"
                          v-bind:post="post"
                          v-on:enlarge-text="onEnlargeText"></blog-post>
            </div>
         </div>
     

VUE.JS Vue.JS

When user clicks the button the v-on:click="$emit('enlarge-text')" will trigger then calling the function onEnlargeText() in the parent当用户单击button时, v-on:click="$emit('enlarge-text')"将触发然后调用父级中的函数onEnlargeText()

         //component (child)
         Vue.component('blog-post', {
             props: ['post'],
             template: `
              <div class="blog-post">
                 <h3>{{ post.title }}</h3>
                 <button v-on:click="$emit('enlarge-text')">
                     Enlarge text
                 </button>
                 <div v-html="post.content"></div>
             </div>`
         })

         //parent
         new Vue({
            el: '#blog-posts-events-demo',
            data: {
               posts: [
                    { id: 1, title: 'My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun' }
               ],
            postFontSize: 1
         },
         methods:{
            onEnlargeText:function(){
               this.postFontSize++;
            }
          }
        })

Actually props suck sometimes you got some old external library in jquyer and need just damn pass value.实际上,道具有时很糟糕,您在 jquyer 中有一些旧的外部库,只需要该死的传递值。 in 99% of time use props that do job but.在 99% 的时间里,使用那些能起到作用的道具。

A) spend tons of hours debuging changing tones of code to pass variables B) one line solution A)花费大量时间调试更改代码色调以传递变量 B)一行解决方案

Create main variable in data letmeknow as object {}在数据中创建主变量 letmeknow 作为对象 {}

this.$root.letmeknow this.$root.letmeknow

then somewhere in code from component然后在组件的代码中的某个地方

this.$root.letmeknow = this;这个.$root.letmeknow = 这个;

and then boom i got component console.log( this.$root.letmeknow ) and see now can change some values然后繁荣我得到了组件console.log(this.$root.letmeknow),现在看到可以改变一些值

暂无
暂无

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

相关问题 Vue JS 3:如何将数据从一个组件传递到另一个组件? - Vue JS 3: How to pass data from one component to another other? 如何将数据从一个组件传递到另一个组件并将该数据存储到 vue.js 中的数组中? - How to pass data from one component to another component and store that data into an array in vue.js? 如何将数据(书籍数组长度)从一个组件传递到 vue.js 中的另一个组件? - How to pass data(books array length) from one component to another component in vue.js? vue.js中如何将一个组件的卡数据绑定到另一个组件卡? - How to bind card data from one component to another component card in vue.js? 如何从 vue js 中的另一个组件获取 boolean 数据? - How can i get boolean data from another component in vue js? 无法在Vue.JS中将数据从一个组件推送到另一个组件 - Unable to push data from one component to another in Vue.JS 如何在组件vue js的数据中引用来自同一组件的方法 - how can I reference a method from the same component in the data of the component vue js 如何在 Vue.js 中将数据从父组件传递到子组件? - How can i pass data from parent component to a child component in Vue.js? 在 React/Next.js 中,如何简单地将数据从一个页面的组件传递到另一个页面上的组件? - How can I simply pass data from a component one page to a component on another page in React/Next.js? React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件? - React - How can I pass API data from one component to another in a different js file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM