- 也称为Bus / 总线 / 发布订阅模式 / 观察者模式
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
// Vue.use(axios)
Vue.config.productionTip = false
Vue.prototype.bus = new Vue() // bus定义,在vue的实例中都会有bus这个属性
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
<!--partOne.vue组件-->
<template>
<div>
<transition name="slide-fade">
<div class="part" v-if="show" @click="show = !show">
{{this.msg}}--
</div>
</transition>
<span @click="busValue">bus传值</span>
</div>
</template>
<script>
export default {
name: 'Part',
data() {
return {
msg: '这是第一部分',
show: true,
valueOne: '这是partOne'
}
},
methods: {
busValue() {
this.bus.$emit('change', this.valueOne)
}
}
}
</script>
<!--partTwo.vue组件-->
<template>
<div class="part">
{{this.msg}}
</div>
</template>
<script>
export default {
name: 'Part',
data() {
return {
msg: '这是第二部分',
valueTwo: ''
}
},
mounted() {
let that = this;
this.bus.$on('change', function(arr) {
that.valueTwo = arr;
console.log(that.valueTwo); // 这是partOne
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" scoped>
</style>
- 通过localStorage或者sessionStorage来存储数据
setItem存储value
用途:将value存储到key字段
用法:.setItem( key, value)
代码示例:
sessionStorage.setItem("key", "value"); localStorage.setItem("site", "...");
getItem获取value
用途:获取指定key本地存储的值
用法:.getItem(key)
代码示例:
let value = sessionStorage.getItem("key"); let site = localStorage.getItem("site");