vue组件通信,Vuex使用,vue-router传值。
纪念入行2年,闲来无事,写点东西。
父组件(home)传值给子组件(son)
父组件
<template>
<div class="home">
<son
:msg="msg"
:val="val"
/>
</div>
</template>
<script>
import son from '@/components/son.vue'
export default {
name: 'Home',
data() {
return {
msg: '我是父组件',
val: 'error'
}
},
components: {
son
}
}
</script>
子组件
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<ul>
<li
v-for="(v,i) in arr"
:key="i"
>{{v}}</li>
</ul>
<div>{{val}}</div>
</div>
</template>
<script>
export default {
name: 'Son',
props: {
msg: String,
arr: {
type: Array,
//对象和数组的默认值必须从一个工厂函数中获取
default: function() {
return [1, 2, 3, 4, 5, 7]
},
//必填
required: true
},
val: {
type: String,
//校验失败会给出警告
validator: function(value) {
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
}
</script>
子组件(son)传值给父组件(home)
子组件
<template>
<div class="hello">
<input v-model="value" />
<button @click="getValue">给父组件</button>
</div>
</template>
<script>
export default {
name: 'son',
data() {
return {
value: ''
}
},
methods: {
getValue() {
this.$emit('getInputValue', this.value)
}
}
}
</script>
父组件
<template>
<div class="home">
<son @getInputValue="getValue" />
<div>我是子组件传过来的value:{{value}}</div>
</div>
</template>
<script>
import son from '@/components/son.vue'
export default {
name: 'Home',
data() {
return {
value: ''
}
},
methods: {
getValue(v) {
this.value = v
}
},
components: {
son
}
}
</script>
通过中央数据总线,实现了任何组件间的通信,包括父子、亲兄弟、跨级
公共bus.js
import Vue from 'vue' export default new Vue()
发送数据的组件
<template>
<div class="hello">
<input v-model="value" />
<button @click="getValue">给别的组件</button>
</div>
</template>
<script>
import Bus from '../store/bus.js'
export default {
name: 'son',
data() {
return {
value: ''
}
},
methods: {
getValue() {
Bus.$emit('getInputValue', this.value)
}
}
}
</script>
监听数据的组件
<template>
<div class="hello">
<div>等别的组件给我传值:{{data}}</div>
</div>
</template>
<script>
import Bus from '../store/bus.js'
export default {
name: 'son1',
data() {
return {
data: ''
}
},
mounted() {
Bus.$on('getInputValue', v => {
this.data = v
})
}
}
</script>
vuex 数据仓库
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cityName: '北京' }, mutations: { changeCityName(state, name) { state.cityName = name } } })
组件中
<template>
<div class="home">
<div>{{cityName}}</div>
<input
type="text"
v-model="city"
/>
<button @click='changeCity'>修改城市名称</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
data() {
return {
city: ''
}
},
methods: {
...mapMutations(['changeCityName']),
changeCity() {
this.changeCityName(this.city)
}
},
computed: {
...mapState(['cityName'])
}
}
</script>

浙公网安备 33010602011771号