题目可能描述的不清楚
请看具体需求:
header.vue 封装的全局的 头部组件,带一个搜索框,所有页面都会引入这个这个header
`
<div style="width:326px;margin:0 100px">
<el-input placeholder="请输入搜索内容" class="input-with-select" v-model="keyword">
<el-button slot="append" icon="el-icon-search" @click="search"></el-button>
</el-input>
</div>
`
其中这个search方法 带着分页参数跳转到 detail.vue组件,这个组件中也引入了header.vue
`
search() {
this.$router.push({
path: '/detail',
query:{
currentPage:1,
size:10,
keyword:this.keyword
}
});
this.keyword = "";
}
`
在detal.vue中 拿到传递来的参数 进行搜索查询 返回结果 展示结果
`
created() {
this.keyword = this.$route.query.keyword;
let data = {};
data.currentPage = this.$route.query.currentPage;
data.size = this.$route.query.size;
data.query = {};
data.query.keyword = this.keyword;
this.getSearch(data);
}
},
`
到这里 逻辑没有问题
问题出在下面
当在detail.vue 这个组件中 header的input里面输入 关键字搜索的时候
也同样走this.search的方法
但是 created不执行 url里面的 参数貌似也没有变化
求问 这个时候 要怎么写 才能在detail.vue中同样能执行搜索查询
或者有别的思路吗
"url里面的 参数貌似也没有变化"可能是你写法有问题。跳转到相同路由时,组件不会刷新,生命周期也不会执行。当你的参数变化时,可以监听route
变化。
watch:{
"route"(to,from){
this.keyword = to.query.keyword;
let data = {};
data.currentPage = to.query.currentPage;
data.size = to.query.size;
data.query = {};
data.query.keyword = this.keyword;
this.getSearch(data);
}
}
###不是应该 watch 吗?
###你的组件detail
,created
生命周期不执行?还是方法不执行?生命周期肯定是执行了。
然后你的header
组件,search
就是一个跳转;你detail
引用了header
组件,你点击search
,肯定执行的是header
中定义的search
方法呀! 你想要在detail
中执行搜索,detail
必须监听header
中的触发search
的操作,header
组件中就要有个$emit
触发,detail
才能监听到。
// header
methods: {
onSearch() {
this.$emit('search', [可选参数])
}
}
// detail
<template>
<div>
<header @search="handleSearch"></header>
// ...
</div>
</template>
methods: {
handleSearch(params) {
// TODO...
}
}
###header组件可以通过$emit 触发details组件的方法
###子组件的方法在父组件运行的时候生命周期就已经运行了,你可以console调试一下就知道什么原因了,用$emit,所有控制方法在父组件里执行
watch监听keyword改变执行函数