javascript 如何在 Vue Js 中将数据值从一个组件更改为另一个组件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46584043/
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
How can I change data value from one component to another component in Vue Js?
提问by Sukanta Bala
I am new in Vue Js. So, I am facing a problem to changes data value from another component.
我是 Vue Js 的新手。因此,我面临着从另一个组件更改数据值的问题。
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. But it cannot be affected component B data. I want to data changes of component B from component A. How can I do that?
它仍然是组件 B 的数据。但它不会受到组件 B 数据的影响。我想从组件 A 获取组件 B 的数据更改。我该怎么做?
Please explain me in details. I have seen vue js props attribute but I don't understand.
请给我详细解释。我见过 vue js props 属性,但我不明白。
回答by mutantkeyboard
回答by truefalse10
You can pass down props to the component B. These props can be updated by the parent component. You can think of B as a stupid component that just renders what the parent tells it to rendern. Example:
您可以将 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>
回答by Chathula Sampath Perera
There are few ways...
有几种方法...
if your components have a parent child relationship you can pass data values from parent into child.
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.
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.
如果您的组件具有父子关系,您可以将数据值从父级传递给子级。
如果您想在子组件更改某些内容时与父组件通信,您可以使用 vuejs 事件发射器(自定义事件)在数据值更改时发出事件,并且该事件可以在另一个组件中侦听并执行您想要的操作。
如果您的组件没有关系,那么您必须使用除上述内容之外的其他内容。可以用两个东西,一个是事件总线,一个是状态管理库。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.
本文档包含您想知道的一切。我不想放任何代码,因为doc很清楚。
VueX is the most preferable way to do this! Very easy to use..
VueX 是最可取的方法!非常容易使用..
回答by NJY404
//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-buttoncomponent is clicked triggers an event add-valuethat calls doSomething()function, then updates the value & show it to my-viewercomponent.
首先,您需要一个父组件,以便两个组件可以通信。当my-button组件被点击触发一个事件add-value的呼叫doSomething()功能,然后更新值显示它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)
使用 props 将数据传递给子组件(父到子)
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-forwill loop on posts and pass data to blog-postcomponent
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)
监听子组件事件(Child to Parent)
HTML
HTML
You must first register the event by v-on:enlarge-text="onEnlargeText"to use $emitand make sure that it's always set to lower case or it won't work properly. example enlargeTextand Enlargetextwill always be converted to enlargetext, thus use enlarge-text instead, because its easy to read & valid, for a brief explanation about $emityou can read it here
您必须首先注册该事件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
Vue.js
When user clicks the buttonthe 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++;
}
}
})

