在父组件中引入子组件
<template>
<child-component></child-component>
</template>
<script>
import childComponent from './components/childComponent'
export default {
name: 'parentComponent',
components: {
childComponent
}
}
</script>
父传子
父组件
<template>
<child-component :sendList="pList" ></child-component>
</template>
<script>
import childComponent from './components/childComponent'
export default {
name: 'parentComponent',
components: {
childComponent
},
data() {
return {
pList: []
}
},
methods: {
getList() {
getListAxio().then(response => {
this.pList = response.data
})
},
}
}
</script>
子组件
<template>
<div class="nodata" v-if="sendList.length<=0">
暂无数据
</div>
<div v-else>
<div v-for="(item,index) in sendList" :key="index" >
{{item}}
</div>
</div>
</template>
<script>
export default {
props: ['sendList']
}
</script>
子传父
子组件
<template>
<el-button @click="sendMsg" size="small" type="primary">确定</el-button>
</template>
<script>
export default {
data() {
return {
aaa: '111'
}
},
methods: {
sendMsg() {
this.$emit('sendMessage', this.aaa)
}
}
}
</script>
父组件
<template>
<child-component @sendMessage="message"></child-component>
</template>
<script>
import childComponent from './components/childComponent'
export default {
name: 'parentComponent',
components: {
childComponent
},
data() {
return {
bbb:''
}
},
methods: {
message(val) {
this.bbb = val // 111
},
}
}
</script>
兄弟传值
兄弟之间可以通过vue官网的方法,在这里介绍一下vuex的方法
-
建立store
image.png
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
},
getters
})
export default store
user.js
const system = {
state: {
list: '',
updateStatus: false,
},
mutations: {
SET_LIST: (state, sendlist) => {
state.list = sendlist
},
UPDATE_STATUS: (state, sendupdateStatus) => {
state.updateStatus = sendupdateStatus
},
}
}
export default user
getters.js
const getters = {
// app首页管理
list: state => state.user.list,
updateStatus: state => state.user.updateStatus
}
export default getters
发送方
<script>
export default {
data() {
return {
myList:[]
}
},
methods: {
// 预览banner
getMyList() {
getList().then(response => {
this.myList = response.data
this.$store.commit('SET_LIST', this.myList)
this.$store.commit('UPDATE_STATUS', true)
})
},
}
}
</script>
接收方
<script>
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'list',
'updateStatus'
])
},
watch: { //通过监听watch,可以根据接收数据的变化做相应的操作
updateStatus() {
if (this.updateStatus) {
alert(1)
}
},
list: { //深度监听
handler(newValue, oldValue) {
console.log(newValue)
},
deep: true
}
},
}
</script>
网友评论