我有2个组成部分
我的第一个组件是这样的:
'link_description' => ($link_description) ? $link_description : AdSeat::whereId(5)->value('link_description),
我的第二个组件是这样的:
<template>
...
<b-form-input type="text" class="rounded-0" v-model="keyword"></b-form-input>
<b-btn variant="warning" @click="search"><i class="fa fa-search text-white mr-1"></i>Search</b-btn>
...
</template>
<script>
export default {
data () {
return {
keyword: ''
}
},
methods: {
search() {
this.$root.$emit('keywordEvent', this.keyword)
location.href = '/#/products/products'
}
}
}
</script>
我使用<template>
...
</template>
<script>
export default {
data () {
return{
keyword: ''
}
},
mounted: function () {
this.$root.$on('keywordEvent', (keyword) => {
this.keyword = keyword
})
this.getItems()
},
methods: {
getItems() {
console.log(this.keyword)
....
}
}
}
</script>
在组件之间传递值
我想将emit
的值传递给第二个组件
keyword
是第二部分
我在第二部分尝试/#/products/products
。但是没有结果
我该如何解决这个问题?
更新:
我有index.js,其中包含如下所示的vue路由器:
console.log(this.keyword)
答案 0 :(得分:1)
通过此代码...
location.href ='/#/产品/产品'
我假设/#/products/products
通过vue-router映射到您的“ second” 组件,我将keyword
定义为路由的查询参数。例如
{
path: 'products',
name: 'products',
component: Products,
props: (route) => ({keyword: route.query.keyword}) // set keyword query param to prop
}
然后,在您的组件中,将keyword
定义为字符串道具(并将其从data
中删除)
props: {
keyword: String
}
使用而不是直接设置location.href
,而是使用
this.$router.push({name: 'products', query: { keyword: this.keyword }})
答案 1 :(得分:0)
在Vue中有一些方法可以实现。
event-bus.js
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;
component1.vue:
import EventBus from './event-bus';
...
methods: {
my() {
this.someData++;
EventBus.$emit('invoked-event', this.someData);
}
}
component2.vue
import EventBus from './event-bus';
...
data(){return {changedValue:""}},
...
mounted(){
EventBus.$on('invoked-event', payLoad => {
this.changedValue = payload
});
}
store / index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = () =>
new Vuex.Store({
store: {myStore:{value:0}},
actions:{["actionName"]:function({commit}, data){commit("actionName", data);}}, // I usualy using special constant for actions/mutations names, so I can use that here in code, and also in components
mutations:{["actionName"]:function(state, data){state.myStore.value = data;}},
getters:{myStoreValue: state => !!state.myStore.value}
})
component1.vue
...
methods:{
change:function(){
this.$store.dispatch("actionName", this.someData); //nuxt syntax, for simple vue you have to import store from "./../store" also
}
}
component2.vue
...
data(){return {changedValue:""}},
...
mounted(){
this.changedValue = this.$store.getters.myStoreValue;
}