vue----webpack模板----组件复用解决方法

组件复用

 
当前组件被复用(没有被销毁或者创建)的时候,路径会发生改变,但是,值不会发生改变
 
因为:created(){}接收值,但是created只创建一次,在create中接收路径传来的值,所以接收到的值不会发生改变
 
 
解决方法:监听路由的变化 $route()
 
使用场景:
    当 一个组件被复用的时候,虽然路由发生变化,但页面上的数据不会发生变化
  比如:
    从列表页list点击商品,进入商品详情页details查看商品的详细信息,当点击商品时,跳转到详情页,并通过路由传递商品的相关信息,详情页
接收商品的详细信息,此时,详情页就会被复用

解决组件被复用,值不能改变的方法-----------监听路由的变化,那个组件复用,在哪个组件监听

方法1:
watch:{
"$route"(to,from){//console.log(this);//vue 的一个实例 //console.log(to);//我要到达的路由的详细信息(即所监听的组件) this.name = to.params.name; this.price = to.params.price; console.log(from) } }, 方法2: beforeRouteUpdate (to, from, next) { // 在当前路由改变,该组件被复用时调用 // 可以访问组件实例 `this`
 this.name = to.params.name;
 this.price = to.params.price;
 next()
  //next根据to的path/name进行路由的跳转,如果不写next,当前路由不会执行
  //当前在a路由,再次点击a路由,不会发生跳转,因为没有让自己跳转,必须要用next
 
},

举例:

<template>
  <div id="details">
    商品名称:{{name}}<br> 商品价格:{{price}}
    <br>商品id:{{id}} </div>
</template>

<script>
export default {
  data () {
    return {
      name: "1",
      price: "1",
      id: "1",
    }
  },
  created () {
    this.name = this.$route.query.name;
    this.price = this.$route.query.price;
    this.id = this.$route.query.id;
    // let { name, price, id } = this.$route.query;
    // this.name = name;
    // this.price = price;
    // this.id = id;
    // console.log(this.$route.query);

  },
  //方法1
  // watch: {
  //   "$route" (to, from) {
  //     console.log(to, from);
  //     this.name = to.query.name;
  //     this.price = to.query.price;
  //     this.id = to.query.id;
  //   }

  // }
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,该组件被复用时调用
    // 可以访问组件实例 `this`
    // console.log(this);
    // console.log(to);
    // console.log(from);
    // console.log(next)
    this.name = to.query.name;
    this.price = to.query.price;
    this.id = to.query.id;
    next()

  },

}
</script>

<style>
</style>
原文地址:https://www.cnblogs.com/SRH151219/p/10427875.html