vue中各种通信传值方式总结

2020-06-14 06:14:47易采站长站整理

}
}
}
</script>
<style scoped>

</style>

Head父组件代码


<template>
<div id="head">
<About @child-message = "handleText"></About> //这里传过来父组件需要用一个方法接住
<p>来自子组件的消息:{{message}}</p>
</div>

</template>

<script>
import About from '@/components/About.vue'
export default {
name: 'Head',
components:{
About
},
data () {
return {
message : ""
}
},
mounted(){

},
methods:{
handleText(data){ //这里的data就是子组件传过来的内容
this.message = data
}
}
}
</script>
<style scoped>

</style>

5、vuex状态管理

状态管理使用起来相对复杂,但是对于大型项目确实非常实用的。

(1)安装vuex,并建立仓库文件


npm install vuex -s

安装过后在src文件中创建store文件夹,并建立index.js文件,index.js的代码如下:


import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
state: {
message: '我是阿格斯之盾'
},
mutations: {
MESSAGE_INFO (state,view) {
state.message = view;
}
}
})
export default store

(2)在min.js中注册store仓库 代码如下:


import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})

(3)状态的读取和提交 还是使用上面的案例,我们以子组件About提交改变状态,父组件Head接受状态并显示出来下面是About组件提交状态


<template>
<div id="about">
<button @click="handleChange">点击发送消息给父组件</button>
</div>
</template>

<script>

export default {
name: 'About',
props:{
'text':[] },
data () {
return {
message: ""
}
},
mounted(){

},
updated(){

},
methods:{
handleChange(){
this.$store.commit("MESSAGE_INFO" , "我是火车王") //提交改变状态
}
}
}
</script>
<style scoped>

</style>

Head组件接受状态:


<template>
<div id="head">
<About></About>