Vue.js 在组件之间传递数据 [英] Vue.js passing data between components
问题描述
我想存储来自 App.vue 的输入值,并在另一个组件中使用它.我该怎么做?我不需要在模板中显示值,我只需要其他组件函数中的值.在 JS 中,我可以只使用全局变量,但如何在 Vue 中实现它?
App.vue:
<div id='应用程序'><!-- App.vue 有搜索栏--><b-form-input @keydown='search' v-model='input'></b-form-input><div><!-- 这是我的其他组件--><路由器视图/>
</模板><脚本>导出默认{name: '应用程序',数据 () {返回 {输入: '',价值: ''}},方法: {搜索 () {this.value = this.inputthis.input = ''}}}
另一个组件:
<div><p>我是另一个组件</p><p>App.vue 输入值是:{{value}} </p>
</模板><脚本>导出默认{道具:['价值'],数据 () {返回 {价值: ''}}}
这是我试图实现的基本逻辑.App.vue 中的输入值 --> anotherComponent.vue
如果组件不是父子组件,您可以为此使用 store:
更高级的
vuex
商店,应该是您的默认 转到 - NPM.或者使用 js 对象的简单解决方案.
一个.创建
store.js
文件并导出具有您将在其中存储值的属性的对象.B.将
store.js
对象导入到 vue 脚本中,然后像这样简单地使用它:
从'store.js'导入商店存储值
I want to store input-value from App.vue, and use it in another component. How can I do it? I don't need the show the value in the template, I just need the value inside other components function. In JS I could just use a global var, but how can I achieve it in Vue?
App.vue:
<template>
<div id='app'>
<!-- App.vue has search bar -->
<b-form-input @keydown='search' v-model='input'></b-form-input>
<div>
<!-- Here's my other components -->
<router-view />
</div>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
input: '',
value: ''
}
},
methods: {
search () {
this.value = this.input
this.input = ''
}
}
}
</script>
Another component:
<template>
<div>
<p>I'm another component</p>
<p>App.vue input value was: {{value}} </p>
</div>
</template>
<script>
export default {
props: ['value'],
data () {
return {
value: ''
}
}
}
</script>
This is the basic logic I'm trying to achieve. Input value in App.vue --> anotherComponent.vue
If components are not parent and child you can use store for this:
More advanced
vuex
store that should be your default GO TO - NPM.Or simple solution with js object.
a. Create
store.js
file and export object with property in which you will store value.b. Import
store.js
object to vue scripts and use it simply like:
import Store from 'store.js'
Store.value
这篇关于Vue.js 在组件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!