Vue笔记(六)——Vue组件通信&Vuex

11次阅读

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

组件通信
vue 本身的组件通信

父 ==> 子:父组件向子组件传参或者调用子组件的方法
子 ==> 父:子组件向父组件传参或者调用父组件的方法
兄弟之间:兄弟组件之间传参或者调用方法

父子通信
传参 – props
思路:定义子组件的属性(自定义),父组件赋值给子组件
调用方法(1)– $refs
思路:定义子组件的属性 -ref=”a”, 父组件通过:this.$refs.a. 子组件方法 ();

调用方法(2)– children
思路:父组件通过:this.$children[0]. 子组件方法 ();

子父通信
调用方法(1)– $parent.$emit(“ 父组件自定义事件 ”);

思路:父组件在组件的生命周期(mounted)用 $on 定义事件,子组件用 this.$parent.$emit(“ 父组件自定义事件 ”);

调用方法(2)– $emit(“ 父组件自定义事件 ”);

思路:父组件在调用子组件时用 v -on 把事件传给子组件,子组件用 this.$emit(“ 父组件自定义事件 ”) 调用父组件传过来的事件
<div id=”app”>
<h1> 父组件 -{{this.text}}</h1>
<!– 子组件 –>
<child v-on:parentEvent=”changeText()”></child>
</div>
<script type=”text/javascript”>
var vm = new Vue({
el:”#app”,
data:{
text:”
},
methods:{
changeText(_text){
this.text = _text;
}
},
components:{
‘child’:{
template:'<p><label> 子组件 </label><input type=”text” v-on:input=”change” /></p>’,
methods:{
change(event){
this.$emit(‘parentEvent’,event.target.value);
}
}
}
}
});
</script>
调用方法(3)– parent
思路:父组件在调用子组件时用 v -on 把事件传给子组件,子组件用 this.$parent. 父组件事件

<div id=”app”>
<h1> 父组件 -{{this.text}}</h1>
<child></child>
</div>
<script type=”text/javascript”>
var vm = new Vue({
el:”#app”,
data:{
text:”
},
methods:{
changeText(_text){
this.text = _text;
}
},
components:{
‘child’:{
template:'<p><label> 子组件 </label><input type=”text” v-on:input=”change” /></p>’,
methods:{
change(event){
this.$parent.changeText(event.target.value);
}
}
}
}
});
</script>
兄弟之间的通信
和上面介绍的父子之间通信是一样的,因为任何连个子组件之间都会拥有一个共同的父级组件,所以兄弟组件之间的通信就是子 1 向父,然后父向子 2,这样来达到兄弟之间组件的通信
Vuex – 状态管理通信
跨组件通信的一种实现方式

用到就封装一个组件.js
组件.js

// 设置属性:state
const state = {
count = 0;
}
// 设置方法:mutaions
const mutaions = {
increment(_state){
_state.count += 1;
}
}
// 执行方法
const actions = {
increment(_content){
_content.commit(‘increment’);
}
}
// 暴露
export default{
state,
mutaions,
actions
}
集合实例化 store.js
import Vue from ‘Vue’;
import Vuex from ‘vuex’;
// 引入组件.js
import transition from ‘./transion.js’;
// 实例化对象
const store = new Vue.Store({
modules:{
transition
}
});
// 暴露对象
export default store;
主入口 app.js 实例化 vuex 对象
// 引入 vuex 对象
import store from ‘./vuex/store.js’;
// 实例化 vuex 对象
new Vue({
el:”#app”,
router,
store,
render:h=>h(app)
});
各组件之间调用
1. 调用参数
$store.state. 组建名. 属性
2. 调用方法
$store.dispatch(‘ 事件名 ’);

正文完
 0