Vue路由 的传值

今天我们讲一下路由的传值
//先在index.js配置路由

 {
      path: '/user/:userId?',//userId时自定义的
      component: User,
      name: 'User'
    }

//路由接受穿过来的id

<router-link :to="{name:'User', params:{userId:item.id}}" 
v-for="(item,index) in userlist" :key='index'>{
   
   {item.name}}
</router-link>

 <p v-show="userinfo.id">
   <span>姓名:{
   
   {userinfo.name}}</span>
   <span>性别:{
   
   {userinfo.sex}}</span>
   <span>喜好:{
   
   {userinfo.like}}</span>
 </p>
  const data = [
  {
    id: 1,
    name: '柯南',
    sex: '男',
    like: '侦探'
  }, {
    id: 2,
    name: '小兰',
    sex: '女',
    like: '空手道'
  }, {
    id: 3,
    name: '小五郎',
    sex: '男',
    like: '喝酒'
  }
]
export default {

  data () {
    return {
      userlist: data,
      userinfo: {}
    }
  },
  created () {
    this.getData()
  },
  methods: {
    // 路由传过来的参数封装
    getData () {
    //接受传过来的id
      let { userId } = this.$route.params
      //判断i d是否为真
      if (userId) {
        this.userinfo = this.userlist.filter(item => {
          return item.id === Number(userId)
        })[0]
      } else {
        this.userinfo = {}
      }
    }
  },
  watch: {
    // 路由发生改变视图实时更新
    $route () {
      this.getData()
    }
  }
}

Supongo que te gusta

Origin blog.csdn.net/woshishui099/article/details/101552547
Recomendado
Clasificación