vue组建传参
一、父子组件传参
vm.$emit( event, arg ) //触发当前实例上的事件
【子传父】借助一个中转的父组件自定义函数,在子组件中利用 $emit 触发父组件的这个中转函数事件,传递的参数作为中转函数的参数传给父组件,
子组件:login.vue
<template>
<section>
<div class="login">
<label>
<span>用户名:</span>
<input type="text" v-model="username" @change="setUser"/>
</label>
</div>
</section>
</template>
<script>
export default {
name: 'footer',
data(){
return{
username:""
}
},
methods: {
setUser(){
//利用transferToParents事件传给父组件
this.$emit('transferToParents',this.username);
}
}
}
</script>
<style scoped>
.login{
position: fixed;
top: 160px;
height:60px;
width: 100%;
background:#333;
color: aliceblue;
line-height: 60px;
}
</style>
父组件:
<p>login组建传过来的参数__用户名:{
{logindata}}</p>
<loginDiv @transferToParents="getUser"></loginDiv>
script中引入子组件,并获取数据
<script>
//引入子组件
import loginDiv from './components/login'
export default {
name:"app",
data(){
return{
logindata:''
}
},
components:{
loginDiv
},
methods: {
getUser(msg){
this.logindata = msg;
console.log('input输入框的值:',msg);
}
}
}
</script>
【父传子】子组件使用props接收父组件的数据。
子组件:
父组件:
二、兄弟组件传参
Vuex该出场了….待续。。。
Vuex都可以什么组件之间都可以传参
假设是组件header和组件content之间的传参:header中input获取的文本值显示在组件content中
组件header,更改author
组件content,实时显示更改的author
vuex的所有配置都写在store.js中,将store.js import到main.js中
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
在mutation中定义更改state状态变量的事件,在组件中使用时,利用this.$store.commit触发调用,才可完成对state的修改。
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
author:"GreyJK"
},
mutations: {
concatAuthor(state,msg){
msg = msg.replace(/([A-Z])/g,' -$&');
state.author = msg;//使用msg该笔author
}
}
})
state:状态
mutation:对state改变的处理事件
组件header,更改author
组件content,实时显示更改的author
组件中使用state中的状态变量author
组件content:
组件header:
input的输入值双向绑定到inputtext
按钮按下调用changeAuthor事件,事件负责提交store.js中的mutation对象的concatAuthor事件。
-——————————————————————————————————————————————————————————————————————————————————-
mapState, mapGetters, mapActions, mapMutations ,这种就是相当于在本组件中给store.js中对应的action、mutation等的方法赋别名…..
mapState, mapGetters, mapActions, mapMutations 就是简化我们的一些 this.$store.state.* 的操作,将this.$store.* 里面的状态 映射到我们辅助函数的属性值里面
方便我们在组件中调用。【https://www.jb51.net/article/138226.htm】
例如:
computed: {
...mapState({
viewsCount: 'views'
}),
...mapGetters({
todosALise: 'getToDo' // getToDo 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 todosALise
})
},
methods: {
...mapMutations({
totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
}),
...mapActions({
blogAdd: 'blogAdd' // 第一个blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,后面一个blogAdd 才是actions里面函数方法名称
})
Vuex 详细的下一篇《Vuex详细讲解》
还没有评论,来说两句吧...