vue2 高级用法
1.bus传参
利用vue实例实现跨一面组件传参方式
新建一个js文件,命名为bus.js。bus.js文件的内容为:
import Vue from 'vue'
const bus = new Vue()
export default bus
使用
bus.$on("colorColorchang",e=>{}) // 接收
bus.$emit("colorColorchang",'red'") // 发送
bus.$off("移除监听") // 卸载这个命令 不写的话,$on事件就会重复执行 有多少事件就卸载多少个
2.跨组件传参
$parent父组件
父组件通过属性绑定,子组件通过props来接收数据进行传值
子组件设置props:
<template>
<div>
<h2>子组件</h2>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
props:["message"]
}
</script>
父组件先引入子组件,而后进行属性绑定
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<child :message="msg"></child>
</div>
</template>
<script>
import child from "./child"
export default {
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
components:{
child
}
}
</script>
$refs.myref dom 引用
在app.vue中
<template>
<div id="app">
<nav>
<button @click="$refs.myref.num+=10">加10</button>
</nav>
<router-view ref="myref" />
</div>
</template>
vuex
// 首先在组件中获取想要的到的参数
this.$store.state.user.info
// 然后在另一个组件的点击事件中修改
change () {
this. $ store.state.user.info = !this.$store.state.user.info
}
cookie.localStorage/sessionStorage
存储本地,需要时可随时调用