可能由于vue用的還是比較少,之前都是用vuex來進(jìn)行變量共享的忠怖,老是忘記呢堰,這里做個(gè)總結(jié),方便后期查詢凡泣。
父子組件傳值
方法:
通過props來進(jìn)行父子組件之間的通信
- 父組件中通過v-bind傳參數(shù)
- 子組件通過props接受參數(shù)
- 依賴注入(另外一種非響應(yīng)式但是可以遞歸傳值的方法請(qǐng)看這篇文章)
例子
<!-- 父組件 -->
<template>
<div>
this is parent
<child :name = "name" v-bind = "options" :arr = "testArr" @test="test"></child>
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
components: {
child
},
data() {
return {
name: 'wcx',
options: {
age: 12,
sex: 'man'
},
testArr: [1,23,4]
}
},
methods: {
test(msg) {
this.name = msg;
}
}
}
</script>
<style lang="less">
</style>
<!-- 子組件 -->
<template>
<div>
{{name}}
{{age}}
{{sex}}
{{arr[1]}}
<button @click = "showmsg">傳值給父組件</button>
</div>
</template>
<script>
export default {
props:{
name: {
type: String,
default: function() {
return 'hello'
}
},
age: Number,
sex: String,
arr: Array
},
data() {
return {
}
},
methods: {
showmsg() {
this.$emit('test', 'child')
}
}
}
</script>
<style lang="less">
</style>
就像上面代碼寫的那樣枉疼,只要v-bind在父組件中的子組件中傳入?yún)?shù)皮假,子組件通過props捕獲即可且不需要在子組件的data中聲明。
子父組件傳值
方法:
通過自定義事件來進(jìn)行父子組件之間的通信
- 在父組件中寫一個(gè)事件以及觸發(fā)后的回調(diào)函數(shù)骂维,并寫好形參惹资。
- 在子組件中用原生事件觸發(fā)一個(gè)回調(diào)函數(shù),里面寫成如下形式:$vm.emit('父組件中定義的xx事件', '要傳的參數(shù)')
例子
同父子組件之間的例子
組件間的傳參
方法:
通過vuex來管理
- 安裝vuex
- Vue.use(vuex)
- 對(duì) vuex中store進(jìn)行實(shí)例化
- 在vue的實(shí)例中傳入store
- 通過
store.commit('store中定義好的方法', '需要傳的參數(shù) ')改變參數(shù)
- 在需要傳參的組件中通過computed和watch進(jìn)行監(jiān)聽捕獲需要的參數(shù)
例子
<!-- 需要傳參的組件 -->
<template>
<div>
this is parent
{{param1}}
<button @click = "test">parentbtn</button>
<child></child>
</div>
</template>
<script>
import child from './child';
export default {
name: 'parent',
components: {
child
},
data() {
return {
param1: this.$store.state.param1
}
},
methods: {
test() {
this.$store.commit('f1', 1)
}
},
//利用computed監(jiān)聽vuex值的變化
computed: {
listenStore() {
return this.$store.state.param1;
}
},
//利用watch監(jiān)聽computed中l(wèi)istenStore函數(shù)的變化并將新值賦給本組件中定義的變量
watch: {
listenStore: {
handler(newValue, oldValue) {
this.param1 = this.$store.state.param1;
},
deep: true
}
}
}
</script>
<style lang="less">
</style>
//main.js 入口js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.config.productionTip = false;
Vue.use(Vuex);//放在最前面
const store = new Vuex.Store({//創(chuàng)建store實(shí)例
state: {
param1: 0
},
mutations: {
f1(state, param) {
state.param1 = param;
}
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,//傳入vue實(shí)例的內(nèi)部
components: { App },
template: '<App/>'
})
``
# 【完】