这星期主要是项目交互,在写评论的时候,我发表评论和遍历评论写到了2个组件里面,所以在发表评论之后,我要再次调用一下遍历评论组件里面的方法,他们2个是兄弟组件,相互用到,所以这个时候就去学习了
o
n
和
on和
on和emit,来实现我想要的效果。他们之间还可以实现从子组件传递数据给父组件。
o
n
是
监
听
数
据
的
,
on 是监听数据的,
on是监听数据的,emit是来发送数据的。
首先我在父组件里面设置一个变量,将这2个兄弟组件联系起来。
在main.js里面写的
const Demo = Vue.extend({})
const d = new Demo()
Vue.prototype.x = d;
我在遍历评论的2那个组件里面用了$on监听数据,
mounted() {
this.showRoot();
this.x.$on('hello',(data)=>{
this.list = data.data
this.commentLen = data.data.length
}),
},
watch:{
list:{
deep:true,
handler(newValue){
this.list = newValue
},
}
},
在发表评论的那个组件里面用$emit来发送数据
this.$http({
url:'/shops/comment/getComment/shop',
methods:'get',
headers:{
'Authorization':cookie.getToken()
},
params:{
shopId:this.$route.params.id
}
})
.then(data => {
this.x.$emit('hello',data.data);
})
.catch(error => {
console.log(error);
})
2.vue组件独享守卫钩子函数
在写搜索功能的时候,如果搜索里面没有内容是不想让他进行跳转的,如果有内容才能进行跳转,然后就用到了独享守卫钩子函数里面的beforeRouteEnter,里面有3个参数,to,from,next,这个函数里面this是没有值的。
<form action="">
<el-input v-model="input" placeholder="请输入店铺名" class='slot'></el-input>
<el-button type="primary">
<!-- 查询 -->
<router-link :to="{
path:'/search',
query:{
content:input
}
}">查询</router-link>
</el-button>
</form>
在要跳转到的页面写上这个钩子函数
beforeRouteEnter(to, from, next) {
// 如果有内容就继续往下进行
if(to.query.content){
next()
console.log(to.query.content);
n = to.query.content
}else{
// 如果没内容就拦截
alert('请输入内容')
}
},
这个函数不能调用this是因为在钩子执行之前,组件实例还没被创建。可以这样写来当做组件实例。
next(vm => {
console.log(vm);//当前组件的实例
});
beforeRouteUpdate(to, from, next) {
//在当前路由改变,但是该组件被复用时调用
//对于一个带有动态参数的路径 /good/:id,在 /good/1 和 /good/2 之间跳转的时候,
// 由于会渲染同样的good组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
console.log(this, 'beforeRouteUpdate'); //当前组件实例
next();
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
console.log(this, 'beforeRouteLeave'); //当前组件实例
next();
}