簡體   English   中英

如何在 Vue Js 中將數據值從一個組件更改為另一個組件?

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

我是 Vue Js 的新手。 因此,我面臨從另一個組件更改數據值的問題。

我有一個組件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);
        }
    }
}

B組份:

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

        }
    }

}

它仍然是 B 組份數據。 但它不會受到 B 組份數據的影響。 我想從組件 A 中獲取組件 B 的數據更改。我該怎么做?

請詳細解釋我。 我看過 vue js props 屬性,但我不明白。

您正在尋找Vuex

它是應用程序中所有數據的集中存儲。

看看他們的文檔,應該很簡單。

您可以將 props 傳遞給組件 B。這些 props 可以由父組件更新。 您可以將 B 視為一個愚蠢的組件,它只渲染父級告訴它渲染的內容。 例子:

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

有幾種方法...

  1. 如果您的組件具有父子關系,您可以將數據值從父級傳遞給子級。

  2. 如果您想在子組件發生更改時與父組件進行通信,您可以使用 vuejs 事件發射器(自定義事件)在數據值更改時發出事件,並且可以在另一個組件中偵聽該事件並執行您想要的操作。

  3. 如果您的組件沒有關系,那么您必須使用除上述內容之外的其他內容。 你可以用兩個東西。一個是事件總線,另一個是狀態管理庫。對於vue,有一個官方的狀態管理庫叫VueX。它非常好用。如果你想使用vuex以外的東西,你可以使用它例如redux,mobx等。

本文檔包含您想知道的一切。 我不想放任何代碼,因為文檔很清楚。

VueX 是最好的方法! 非常好用。。

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>

首先,您需要一個父組件,以便兩個組件可以通信。 當單擊my-button組件時,會觸發一個調用doSomething()函數的事件add-value ,然后更新該值並將其顯示給my-viewer組件。

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

     //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++;
             }
        }
     })

這是基於Vue 組件指南

使用道具將數據傳遞給子組件(父子組件)

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:

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>

監聽子組件事件(子到父)

HTML

您必須首先通過v-on:enlarge-text="onEnlargeText"注冊事件才能使用$emit並確保它始終設置為小寫,否則它將無法正常工作。 示例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

當用戶單擊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++;
            }
          }
        })

實際上,道具有時很糟糕,您在 jquyer 中有一些舊的外部庫,只需要該死的傳遞值。 在 99% 的時間里,使用那些能起到作用的道具。

A)花費大量時間調試更改代碼色調以傳遞變量 B)一行解決方案

在數據中創建主變量 letmeknow 作為對象 {}

this.$root.letmeknow

然后在組件的代碼中的某個地方

這個.$root.letmeknow = 這個;

然后繁榮我得到了組件console.log(this.$root.letmeknow),現在看到可以改變一些值

暫無
暫無

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

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