关于javascript:vue组件chuanc

32次阅读

共计 5096 个字符,预计需要花费 13 分钟才能阅读完成。

组件传参

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' // 引入 vue
import Vuex from 'vuex'  // 引入 vuex
Vue.use(Vuex) // 应用 Vuex
const 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 = false
var echarts = require('echarts')
Vue.prototype.$echarts = echarts
Vue.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('缓存名称'))

正文完
 0