在应用复杂时,推荐使用vue官网推荐的vuex,以下讨论简单SPA中的组件间传值。
一、路由传值
路由对象如下图所示:
在跳转页面的时候,在js代码中的操作如下,在标签中使用<router-link>标签
this.$router.push({
name: 'routePage',
query/params: {
routeParams: params
}
})
需要注意的是,实用params去传值的时候,在页面刷新时,参数会消失,用query则不会有这个问题。
这样使用起来很方便,但url会变得很长,而且如果不是使用路由跳转的界面无法使用。取值方式分别为: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'}})
这种方式会把路由导航到 /OrderDetail/22aead11a99c4c91aa2169ac17d0ddb5/booking 路径
参考:http://router.vuejs.org/zh-cn/essentials/named-routes.html
二、通过$parent,$chlidren等方法调取用层级关系的组件内的数据和方法
通过下面的方法调用:
this.$parent.$data.id //获取父元素data中的id
this.$children.$data.id //获取父元素data中的id
这样用起来比较灵活,但是容易造成代码耦合性太强,导致维护困难
三、采用eventBus.js传值---兄弟组件间的传值
eventBus.js
import Vue from 'Vue' export default new Vue()
App.vue
<template>
<div id="app">
<secondChild></secondChild>
<firstChild></firstChild>
</div>
</template> <script>
import FirstChild from './components/FirstChild'
import SecondChild from './components/SecondChild' export default {
name: 'app',
components: {
FirstChild,
SecondChild,
}
}
</script>
FirstChild.vue
<template>
<div class="firstChild">
<input type="text" placeholder="请输入文字" v-model="message">
<button @click="showMessage">向组件传值</button>
<br>
<span>{{message}}</span>
</div>
</template>
<script>
import bus from '../assets/eventBus';
export default{
name: 'firstChild',
data () {
return {
message: '你好'
}
},
methods: {
showMessage () {
alert(this.message)
bus.$emit('userDefinedEvent', this.message);//传值
}
}
}
</script>
SecondChild.vue
<template>
<div id="SecondChild">
<h1>{{message}}</h1>
</div>
</template>
<script>
import bus from '../assets/eventBus';
export default{
name:'SecondChild',
data(){
return {
message: ''
}
},
mounted(){
var self = this;
bus.$on('userDefinedEvent',function(message){
self.message = message;//接值
});
}
}
四、通过localStorage或者sessionStorage来存储数据(参考:https://blog.****.net/qq_32786873/article/details/70853819)
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");