vue传值方式

一、路由传值
//params使用场景
router.push('/users/123') // 跳转时
router.push({ // 另一种方式跳转
  name: 'users',
  params: {
    id: 123
  }
})
// 获取id
route.params.id // 123
// 实际URL地址 => localhost:8080/users/123

//query使用场景
router.push('books?q=123') // 跳转时
router.push({ // 另一种方式跳转
  path: '/books',
  query: {
    q: 123
  }
})
// 获取query
route.query.q // 123
// 实际URL地址 => localhost:8080/books?q=123
需要注意的是,实用params去传值的时候,在页面刷新时,参数会消失,用query则不会有这个问题。

取值方式分别为:this.$route.params.paramName和this.$route.query.paramName

注:使用params传值,也可以做到页面刷新,参数不丢失,在命名路由时这样设置:
{  
      path: '/OrderDetail/:orderId/:type',  
      name: 'OrderDetail',  
      component: OrderDetail,  
      meta: {  
        title: '订单详情',  
        needAuth: true  
      }  
}  
使用时:
this.$router.push({name: 'OrderDetail', params: {orderId: id, type: 'buy'}})  

<router-link  :to="{name: 'detail', params: {itemId: list.itemid}}">
<router-link :to="{path:'/detail',query: {name: id}}">

二、父传子,子传父(子级不能修改父级传过来的数据)

父传子:

父:
:selections="versionList"
子:
props:{
   selections:{
type:Array,
default:[
   {
   label: 'test',
    value: 0
}]}}

子传父:

子:
this.$emit("on-change",{list:this.giftList[this.nowIndex],msg:this.giftMsg})

父:
<v-layerRedp  @on-change="onsendRedp"></v-layerRedp>
三、通过eventBus传递数据(用于单页面之间)
全局定义一个eventBus
mport Vue from 'vue'
const eventBus = new Vue()
export { eventBus }

在需要传递参数的组件中,定义一个emit发送需要传递的值
eventBus.$emit('eventBusName', id);

在需要接受参数的组件重,用on接受该值(或对象)
//val即为传递过来的值
eventBus.$on('eventBusName', function(val) {
 console.log(val)
})

最后记住要在beforeDestroy()中关闭这个eventBus
eventBus.$off('eventBusName');

a.vue
eventBus.$emit('empty-redp') //触发一个事件
b.vue
//在mounted里监听empty-msg事件的同时,执行回调函数
eventBus.$on('empty-redp',()=>{
    this.total=''
    this.num=''
    this.msg=''
})

五、localStorage或者sessionStorage来存储数据

setItem存储value
用途:将value存储到key字段
用法:.setItem( key, value)
代码示例:
sessionStorage.setItem("key", "value"); 
localStorage.setItem("site", "js8.in");

getItem获取value
用途:获取指定key本地存储的值
用法:.getItem(key)
代码示例:
var value = sessionStorage.getItem("key"); 
var site = localStorage.getItem("site");


猜你喜欢

转载自blog.csdn.net/qq_14993375/article/details/79607762