组件传参
1、父组件像子组件传参
1.1父组件通过 v-bind/ : 传参数给子组件
留神:
参数名需用应用-代替驼峰
父组件:
<add :msg-val="msg"></add>data(){ return { msg: [1,2,3] };}
1.2子组件通过props办法承受参数
props中能够通过定义default设置能承受的收据类型,如果不合乎会报错
子组件:
props: ['msgVal']props: { msgVal: Array //这样能够指定传入的类型,如果类型不对,会正告} ||props: { msgVal: { type: Array, //指定传入的类型 //type 也能够是一个自定义结构器函数,应用 instanceof 检测。 default: [0,0,0] //这样能够指定默认的值 }}<span>{{msgVal}}</span>
留神:父子传参,数据是异步申请,可能在数据渲染时会报错
起因:异步申请时,数据还没有获取到但此时可能曾经渲染到该节点了
解决:(1)能够在父组件须要传递数据的节点上增加v-if,默认为false,异步申请获取数据后为true
(2)在vue中能够应用this.$nextTick(() => {})解决异步操作
2、子组件触发父组件办法并传参
2.1子组件通过$emit触发父组件办法
父组件通过 v-on:办法名 定义方法
<blog-post v-on:enlarge-text="postFontSize += 0.1"></blog-post>
子组件通过 $emit('办法名') 触发办法
<button v-on:click="$emit('enlarge-text')">Enlarge text</button>
2.2 子组件调用父组件办法并传参
子组件通过 $emit 触发办法,且第二个参数就是须要传递给父组件的参数
<button v-on:click="$emit('enlarge-text', 0.1)">Enlarge text</button>
父组件通过 $event 拜访子组件抛出的参数
<blog-post v-on:enlarge-text="postFontSize += $event"></blog-post> <blog-post v-on:enlarge-text="onEnlargeText"></blog-post>methods: { onEnlargeText: function (enlargeAmount) { this.postFontSize += enlargeAmount }}
3、子组件向子组件传参
vue中没有子组件向子组件传参的办法,倡议将须要传参的子组件合并为一个大组件
如果肯定要子组件向子组件传参,有两种办法
(1)有父组件
能够先由一个子组件传参给父组件,再传给子组件
(2)无父组件
通过eventBus或vuex(小我的项目少页面用eventBus,大我的项目多页面应用 vuex)传值
3.1 通过eventBus(即通过v-on监听,$emit触发)
3.1.1定义一个新的vue实例专门用来传递数据,并导出
`eventBus.js
import Vue from 'vue'
export default new Vue()`
3.1.2 定义传递的办法名和传输内容,点击事件或钩子函数触发eventBus.emit事件
componentA.vue
<template> <div class='componentA'> <button @click="emitToB">点击按钮传递数据给兄弟组件B</button> </div></template><script> import eventBus from 'api/eventBus.js' export default { methods: { emitToB() { eventBus.$emit('eventFORMA', '我是组件A传递给组件B的数据') } } }</script>
3.1.3 承受传递过去的数据
留神:eventBus是一个新的vue实例,辨别两个this所示意的实例
compontB.vue
<template> <div class='componentB'> {{title}} //最终显示传递过去的值 </div></template><script> import eventBus from 'api/eventBus.js' export default { data() { return { title: '' } }, mouted() { this.getEventData() }, methods: { getEventData() { const vm = this //这个this是我的项目vue的实例,用vm承受,与eventBus的vue辨别 eventBus.$on('eventFROMA', function(val) { vm.title = val //this.title = val //这里的this指的是eventBus的vue实例 }) } } }</script>
3.2 vuex进行传值
创立Vuex.Store实例保留到变量store中,最初应用export default导出store
store->index.js
import Vue from 'vue' //引入vueimport Vuex from 'vuex' //引入vuexVue.use(Vuex) //应用Vuexconst store = new Vuex.store({ state: { count: 1 }, getters: { getStateCount: function(state) { //state就是下面state return state.count + 1 } }, mutations: { add(state) { state.count = state.count + 1 }, reduction(state) { state.count = state.count - 1 } }, actions: { //注册actions,相似与methods addFun(context) { //承受一个与store实例具备雷同办法的属性得context对象 context.commit('add'') }, reductionFun(context, n) { //承受一个与store实例具备雷同办法的属性得context对象 context.commit('reduction', n) } } })export default store //导出store
在main.js文件中引入该文件,在文件中增加import store from './store,再在vue实例全局引入store对象:
import Vue from 'vue'import App from './App.vue'import router from './router'import store from './store'import ElementUI from 'element-ui'Vue.config.productionTip = falsevar echarts = require('echarts')Vue.prototype.$echarts = echartsVue.use(router)Vue.use(ElementUI, { size: 'mini'})new Vue({ router, store, render: h => h(App)}).$mount('#app')
State:
vuex中的数据源,咱们须要保留的数据就保留在这里,能够在页面通过 this.$store.state来获取咱们定义的数据;
HelloWorld.vue
<template> <div> <h2>{{this.$store.state.count}}</h2> </div></template>
Getters:
Getter相当于vue中的computed计算属性,getter 的返回值会依据它的依赖被缓存起来,且只有当它的依赖值产生了扭转才会被从新计算,这里咱们能够通过定义vuex的Getter来获取,Getters 能够用于监听、state中的值的变动,返回计算后的后果,这里咱们批改HelloWorld.vue文件如下:
<template> <div> <h2>{{this.$store.state.count}}</h2> //1 <h2>{{this.$store.getters.getStateCount}}</h2> //2 </div></template>
Mutations:
数据咱们在页面是获取到了,然而如果咱们须要批改count值怎么办?如果须要批改store中的值惟一的办法就是提交mutation来批改,咱们当初Hello World.vue文件中增加两个按钮,一个加1,一个减1;这里咱们点击按钮调用add(执行加的办法)和reduction(执行减法的办法),而后在外面间接提交mutations中的办法批改值:
<template> <div> <button @click="addFun">-</button> <button @click="reductionFun">+</button> </div></template><script>method: { addFun() { this.$store.commit('add') //add是mutations内的办法 }, reductionFun() { this.$store.commit('reduction') //reduction是mutation中的办法 }}</script>
Actions:
然而,官网并不倡议咱们这样间接去批改store外面的值,而是让咱们去提交一个actions,在actions中提交mutation再去批改状态值,接下来咱们批改index.js文件,先定义actions提交mutation的函数:
<template> <div> <button @click="add">-</button> <button @click="reduction">+</button> </div></template><script>method: { addFun() { this.$store.dispatch('addFun') //addFun是actions内的办法 }, reductionFun() { var n = 10; this.$store.dispatch('reductionFun', n) //reductionFun是actions内的办法 }}</script>
4、切换页面时组件之间的传参
4.1 通过路由携带参数进行传参
A -> B
A组件传参
this.$router.push( { path: '/componentB', //跳转到组件B query: { orderId: 123 }})
B组件接管参数
this.$route.query.orderId
4.1.1传参形式
(1)查问参数query(+path)
查问参数搭配query,刷新页面数据不会失落
(2)命名路由params(+name)
命名路由搭配params,刷新页面参数回失落
承受参数应用this.$router前面就是搭配路由的名称,就能获取到参数的值
4.2 路由导航
(1)申明式的导航
<router-link :to='...'>
(2)编程式的导航
router.push(...)router.replace(...)
4.3 通过设置SessionStorage缓存模式进行传递
A组件缓存orderData
const orderData= { 'orderId':123, 'price': 88'}//sessionStorage生命周期为以后窗口或标签页,一旦窗口或标签页被永恒敞开了,那么所有通过sessionStorage存储的数据也就被清空了。sessionStorage.setItem('缓存名称',JSON.stringify(orderData))//localStorage生命周期是永恒的,除非用户在浏览器提供的UI上革除localStorage信息,否则这些信息将永远存在localStorage.setItem('缓存名称',JSON.stringify(orderData))
B组件获取A中设置的缓存
const dataB = JSON.parse(sessionStorage.getItem('缓存名称'))const dataB = JSON.parse(localStorage.getItem('缓存名称'))